This is a creation in Article, where the information may have evolved or changed.
The sync pack in Golang has a very useful function, which is Waitgroup
Let's talk about the purpose of Waitgroup: it can wait until all the goroutine execute, and block the execution of the main thread until all the Goroutine execution is complete.
Waitgroup a total of three methods: ADD (delta int), done (), Wait (). Simply say the effect of these three methods.
Add: Adds or reduces the number of waiting goroutine
Done: Equivalent to add (-1)
Wait: Perform blocking until all the Waitgroup number becomes 0
Take a look at the example:
Package Mainimport ("FMT" "Sync" " Time") Func main () {varWG Sync. Waitgroup forI: =0; I <5; i = i +1{WG. ADD (1) go func (nint) { //defer WG. Done ()Defer WG. ADD (-1) Echonumber (n)} (i)} WG. Wait ()}func echonumber (iint) {time. Sleep (3e9) fmt. Println (i)}
The results are as follows:
0 1 2 3 4
The program is simple, just output the number of each loop over 3 seconds. Then, if the program does not waitgroup, then the output will not be visible. Because the Goroutine has not finished, the main thread has been executed. Note the defer WG. Done () and defer WG. ADD (-1) acts the same. This is good, the original execution script, all use time. Sleep, with an estimated time until the child thread finishes executing. Waitgroup is very good. Although Chanel can be implemented, it feels good if it involves not having a child thread synchronizing with the main thread data.