drphfy1198 2018-03-30 22:15
浏览 92
已采纳

在Goroutine函数中将数组作为值传递不会执行任何操作

I have something like this:

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)
}

If i do this i get nothing new in someArray, just the zeroes i got in the initialization. I'm sure i need a channel to communicate between the goroutines and the receiving array, but I'm clueless.

Any tips?

Thanks!

EDIT: some working code

  • 写回答

1条回答 默认 最新

  • dongrao9454 2018-03-30 22:57
    关注

    When you put go in front of it, it runs it in a separate goroutine (similar to a thread), and the current code path continues - they are running at the same time.

    This means, that when you do fmt.Println(someArray), you have no guarantee that DoSomethingWithArray has completed. In this instance, you could use a sync.WaitGroup, to let your current thread wait until the other code has completed:

    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()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 docker部署Mongodb后输入命令报错?
  • ¥15 将下列流程图转变成python程序代码
  • ¥15 我需要全国每个城市的最新小区名字等数据。
  • ¥15 开发一个小区生态的小程序
  • ¥15 如何解决Excel中dependent dropdown list 的问题
  • ¥15 MddBootstrapInitialize2失败
  • ¥15 LCD Flicker
  • ¥15 esp32在micropython环境下使用ssl/tls连接mqtt服务器出现以下报错Connected on 192.168.154.223发生意外错误: 5无法连接到 MQTT 代理,如何解决?
  • ¥15 关于#genesiscsheel#的问题,如何解决?
  • ¥15 Android aidl for hal