This is a creation in Article, where the information may have evolved or changed.
Golang Sync Waitgroup
Just looked at Golang's sync bag and saw a very useful feature. 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
Package Mainimport ("FMT" "Sync" "Time") Func main () {var wg sync. Waitgroupfor I: = 0; I < 5; i = i + 1 {WG. ADD (1) go func (n int) {//Defer WG. Done () defer WG. ADD ( -1) echonumber (n)} (i)}WG. Wait ()}func echonumber (i int) {time. Sleep (3e9) fmt. Println (i)}
Output Result:
01234
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.