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 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题