在 Goroutine 函数中将数组作为值传递没有任何作用

Passing an array as value in a Goroutine function does nothing

我有这样的东西:

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 中没有得到任何新东西,只有我在初始化中得到的零。我确定我需要一个通道来在 goroutine 和接收数组之间进行通信,但我一无所知。

有什么建议吗?

谢谢!

编辑:一些工作代码

当你把go放在它前面时,它会在一个单独的goroutine(类似于一个线程)中运行它,并且当前的代码路径继续——它们同时是运行 .

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

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

var wg sync.WaitGroup
func main() {
    someArray := Empty2DArray(4)
    wg.Add(1)
    go DoSomethingWithArray(4,0,someArray)
    wg.Wait()
    fmt.Println(someArray)
}

func DoSomethingWithArray(aSize, threadID int, mapArray [][]int) {
    //your code
    wg.Done()
}