for 循环内的并发 goroutine



我在循环中编写了goroutine,如下所示。我想要的是同时为设备列表中的每个项目执行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()

谁能帮我解决这个问题?提前谢谢。

尝试使用 goroutine 闭包

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

也就是说,ctx变量名在 for 循环中使用之前在 for 循环中被覆盖(因为变量是词法范围的),请参阅这个问题以获得很好的解释 为什么 Golang 在 goroutines 中处理闭包的方式不同?

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

这意味着闭包中引用的任何变量都不是副本,而是引用。

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

它的作用是为所有IP地址创建并行goroutine。

像下面这样做

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

最新更新