for循环中的并发goroutine

时间:2017-01-03 09:48:15

标签: go

我已经在里面写了goroutine for循环如下。我想要的是同时为listofDevices列表中的每个项执行goroutine,但是这个逻辑只对listofDevices列表中的一个项运行goroutine。

    for _, ip := range listOfDevices {
            inChan <- types.NewNotification(time.Now(), "/cloudtracer/status", nil,
                    &map[key.Key]interface{}{
                            key.New(ip): types.Pointer{Pointer: "/cloudtracer/status/" + ip},
                    })
            pingOneMachine := probe.NewPing(ip, 2*time.Second, inChan)
            // For now stopping the probe after few minutes. This will change later
            ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
            defer cancel()

            wg.Add(len(listOfDevices))
            go func() {
                    defer wg.Done()
                    pingOneMachine.Run(ctx)
            }()
    }
    wg.Wait()

任何人都可以帮我解决这个问题吗? 提前谢谢。

3 个答案:

答案 0 :(得分:1)

尝试使用goroutine 闭包

            go func(c context.Context) {
                    defer wg.Done()
                    pingOneMachine.Run(c)
            }(ctx) // pass in the lexically scoped variable here

也就是说,在for循环中使用ctx变量名之前,它在goroutine中使用(因为变量是词法范围的),请参阅此问题以获得一个很好的解释Why does Golang handle closures differently in goroutines? < / p>

基本上变量通过引用传递:

  

这意味着在&#34;外部&#34;范围不是副本,但实际上是参考。

答案 1 :(得分:0)

for ;;{
    wg.Add(1)
    go func(ip string){
        defer wg.Done()
    }(ip)
}
wg.Wait()

它可以为所有ip地址创建并行goroutine。

答案 2 :(得分:-1)

像下面这样做

for ;;{
        wg.Add(1)
        go func(){
            defer wg.Done()
        }
    }
    wg.Wait()