dongwen4487 2018-08-11 03:46
浏览 51

如何同步执行并发初始化切片的go例程?

I am trying to initialize an array of items in concurrently manner using go routines. However, the strange memory behavior of Go prevents me from doing so even I used the suggested primitives (channel). Below is the minimal reproduce:

func TestSliceInit(t *testing.T){
toInit := make([]int, 10)
syncLock := make(chan bool)

for i := range toInit{
    go func(){toInit[i] = i; syncLock <- true}()
}

for range toInit{
    <-syncLock
}

for i := range toInit{
    if toInit[i] != i{
        t.Error("fail to init")
    }
}
}

The code is supposed to initialize the toInit array to 0-9 but it does not. Instead, error will be produced. I tried this code on Goland 2018.1

  • 写回答

1条回答 默认 最新

  • douya1061 2018-08-11 04:06
    关注

    Because the code is run concurrently, your variable i is modified each time a goroutine is called because they all keep a reference to the same variable i

    To prevent that to happen, pass the index parameter to your anonymous function.

    package main
    
    import "fmt"
    
    func main() {
      toInit := make([]int, 10)
      syncLock := make(chan bool)
    
    for i := range toInit{
        go func(i int){
          toInit[i] = i; 
          syncLock <- true}(i)
    }
    
    for range toInit{
        <-syncLock
    }
    
    for i := range toInit{
        if toInit[i] != i{
            fmt.Println("error")
        }
    }
    }
    

    The other way would be to use a declaration style using the following

    for i := range toInit{
            i := i
            go func(){
              toInit[i] = i; 
              syncLock <- true}()
     }
    

    Here is a nice documentation about closures and goroutines

    评论

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?