for循环内的并发goroutines

I have written goroutine inside for loop as follow. What I want is to execute the goroutine for each item in the listofDevices list concurrently but this logic is running goroutine for only one item in the listofDevices list.

    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()

Can anyone help me in fixing this out? thanks in advance.

do it like following

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

Try using the goroutine closure:

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

That is, the ctx variable name is being overridden in the for loop before it is used in the goroutine (as the variables are lexically scoped), see this question for a nice explanation Why does Golang handle closures differently in goroutines?

Basically variables are passed by reference:

This means that any variables referenced within the closure from the "outer" scope are not a copy but are in fact a reference.

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

It worked in creating parallel goroutines for all the ip addresses.