Go provides the sync package and channel to resolve the synchronization and communication. Novice to the channel channel operation is more prone to deadlock, if the buffer channel also consider the channel to put and remove data rate problem.
Literally can be understood, sync. Waitgroup is waiting for a set of coprocessor to end. It implements a structure similar to a task queue, where you can add tasks to the queue, remove tasks from the queue when the task is completed, and trigger blocking to prevent the program from continuing if the tasks in the queue are not completed.
Sync. Waitgroup has only 3 methods, ADD (), done (), wait (). The Done () is the alias of Add (-1). To put it simply, add a count using Add (), do () subtract a count, count is not 0, and block the run of Wait ().
A simple example is as follows:
Package Main
Import (
"FMT"
"Sync"
)
var waitgroup sync. Waitgroup
Func test (shownum int) {
Fmt. Println (Shownum)
Waitgroup. Done ()//task completed, the task queue in the number of tasks-1, in fact. Done is. ADD (-1)
}
Func Main () {
For I: = 0; I < 10; i++ {
Waitgroup. ADD (1)///each create a goroutine, the number of tasks in the queue +1
Go Test (i)
}
Waitgroup. Wait ()//. Wait () This will be blocked until all the tasks in the queue are closed
Fmt. Println ("done!")
}