在Goroutine函数中将数组作为值传递不起作用

时间:2018-03-30 22:15:23

标签: go goroutine

我有这样的事情:

package main

import (
    "fmt"
)

// Empty2DArray returns a zeroed 2D array.
func Empty2DArray(arraySize int) [][]int {
    emptyArray := make([][]int, arraySize)
    for y := 0; y < arraySize; y++ {
        row := make([]int, arraySize)
        for x := 0; x < arraySize; x++ {
            row[x] = 0
        }
        emptyArray[y] = row
    }
    return emptyArray
}

func DoSomethingWithArray(aSize, threadID int, mapArray [][]int) {

    var start, end int

    switch threadID {
    case 0: // unique thread
        start = 0
        end = aSize
    case 1: // 1 and 2 when using more than 1 and less than 2 threads.
        start = 0
        end = aSize / 2
    case 2:
        start = aSize/2 + 1
        end = aSize
    }

    for j := start; j < end; j++ {
        for i := 0; i < aSize; i++ {
            mapArray[i][j] = 1
        }
    }
}

func main() {

    someArray := Empty2DArray(4)
    DoSomethingWithArray(4, 0, someArray) // this works
    //  go DoSomethingWithArray(4,0,someArray) // this doesnt
    fmt.Println(someArray)
}

如果我这样做,我在someArray中没有任何新东西,只是在初始化中得到的零。我确定我需要一个通道来在goroutines和接收阵列之间进行通信,但我很无能为力。

任何提示?

谢谢!

编辑:一些工作代码

1 个答案:

答案 0 :(得分:1)

当你将static Dictionary<string, int> cityList = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); static void SomeMethod(SomeType e) { var weatherQuery = "what is the weather like in"; int cityId; string userInput = e.PartialResult.ToString().Trim(); if (userInput.StartsWith(weatherQuery, StringComparison.OrdinalIgnoreCase) && cityList.TryGetValue(userInput.Substring(weatherQuery.Length).Trim(), out cityId)) { // We have a weather query and have located the cityId CallSomeWeatherAPI(cityId); } } 放在它前面时,它会在一个单独的goroutine(类似于一个线程)中运行它,并且当前的代码路径继续 - 它们同时运行。

这意味着,当您执行go时,您无法保证fmt.Println(someArray)已完成。在这种情况下,您可以使用DoSomethingWithArray,让当前线程等到其他代码完成:

https://play.golang.org/p/zClukrHNdpM

sync.WaitGroup