WaitGroup的用途:它能够一直等到所有的goroutine执行完成,并且阻塞主线程的执行,直到所有的goroutine执行完成. 官方对它的说明如下: A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and…
下面一段代码 len(m) 不一定会打印为 10,为什么?.如果想要 len(m) 打印为 10,应该怎么修改代码? func main() { const N = 10 m := make(map[int]int) wg := &sync.WaitGroup{} mu := &sync.Mutex{} wg.Add(N) for i := 0; i < N; i++ { go func() { defer wg.Done() mu.Lock() m[i] = i mu.Unlock…
问题引入 学习golang(v1.16)的 WaitGroup 代码时,看到了一处奇怪的用法,见下方类型定义: type WaitGroup struct { noCopy noCopy ... } 这里,有个奇怪的"noCopy"类型,顾名思义,这个应该是某种"不可复制"的意思.下边是noCopy类型的定义: // noCopy may be embedded into structs which must not be copied // after the f…