This is a created article in which the information may have evolved or changed.
go provides sync packet and channel to resolve synchronization and communication . The novice is more likely to create deadlocks for channel channels, and if the buffered channel also takes into account the rate at which the channel is put in and out of the data.
Literally can understand, sync. Waitgroup is waiting for a group of threads to end. It implements a similar task queue structure where you can add tasks to the queue, remove the task from the queue when the task is complete, and if the tasks in the queue are not all complete, the queue will trigger blocking to prevent the program from continuing to run.
sync. Waitgroup has only 3 methods, ADD (), Done (), Wait (). where done () is the alias of Add (-1). Simply put, using Add () adds a count, done () minus a count, the count is not 0, and the wait () is blocked from running.
A simple example is as follows:
package main import ("fmt""sync") var waitgroup sync.WaitGroup func test(shownum int) {fmt.Println(shownum)waitgroup.Done() //任务完成,将任务队列中的任务数量-1,其实.Done就是.Add(-1)} func main() {for i := 0; i < 10; i++ {waitgroup.Add(1) //每创建一个goroutine,就把任务队列中任务的数量+1go test(i)}waitgroup.Wait() //.Wait()这里会发生阻塞,直到队列中所有的任务结束就会解除阻塞fmt.Println("done!")}