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

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格