带有通道的循环中的goroutine [关闭]

enter image description here

Note: GetTaskQueue() returns a global variable which struct is

type TaskQueue struct {
    ch   chan int
    wg   *sync.WaitGroup
}

The channel is used to limit the number of goroutines, and the max number of goroutines is set to be 3.

My expectation is that all ts should match the tasks. However, Dominium and dApp Builder did not show in t, while EthicHub Twitter and Apollo duplicated.

The output is shown below.

enter image description here

Loop variables are reused: Every iteration of the for loop uses the same task variable and thus all your goroutines receive the same address.

(And do not post screenshots).

As it was mentioned in the previous answer the address of the task loop variable is always the same. So this should work for you:

for _, task := range tasks {
        t := task
        fmt.Println("task ", t.Name)
        time.Sleep(2 * time.Second)
        go func(t *DB.TaskLog) {
            defer GetTaskQueue().Done()
            fmt.Println("task ", t.Name)
            CrawlAirdrop(t.Link)
        }(&t)

        select {
        case <-ctx.Done():
            return
        default:
        }
}