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: Adds or reduces the number of waiting goroutine
Done: Equivalent to add (-1)
Wait: Perform blocking until all the Waitgroup number becomes 0
Practice
Example 1 differs from Instance 2 code: One line of code is missing go func () {} ()
Example 1 and instance 3 code differences: Runtime. Gomaxprocs's entry is different.
Example 1 (sequential output)
Package Mainimport ("FMT" "Sync" "Runtime") func main () {N: = The runtime. Gomaxprocs (1) var waitgroup sync. Waitgroup Waitgroup.add (2*n) for I: = 1; I <= N; i++ {go func (i int) {//defer Waitgroup.add ( -1) defer waitgroup.done () Fmt. Printf ("%c", + + i)} (i)} for I: = 1; I <= N; i++ {go func (i int) {//defer waitgroup.ad D ( -1) defer waitgroup.done () Fmt. Printf ("%c", + i)} (i)} go func () {} () Waitgroup.wait ()}
Run results
Example 2 (except for the last letter, other character sequential output)
Package Mainimport ("FMT" "Sync" "Runtime") func main () {N: = The runtime. Gomaxprocs (1) var waitgroup sync. Waitgroup Waitgroup.add (2*n) for I: = 1; I <= N; i++ {go func (i int) {//defer Waitgroup.add ( -1) defer waitgroup.done () Fmt. Printf ("%c", + + i)} (i)} for I: = 1; I <= N; i++ {go func (i int) {//defer waitgroup.ad D ( -1) defer waitgroup.done () Fmt. Printf ("%c", + i)} (i)}//go func () {} () Waitgroup.wait ()}
Run results
Z a b c d e F g h i j k l m n o p q R S t u v w x y z a b c d e F g h i j k l m n o p q R S t u v W x y
Example 3 (out of sequence output)
Package Mainimport ("FMT" "Sync" "Runtime") func main () {N: = The runtime. Gomaxprocs (2) var waitgroup sync. Waitgroup Waitgroup.add (2*n) for I: = 1; I <= N; i++ {go func (i int) {//defer Waitgroup.add ( -1) defer waitgroup.done () Fmt. Printf ("%c", + + i)} (i)} for I: = 1; I <= N; i++ {go func (i int) {//defer waitgroup.ad D ( -1) defer waitgroup.done () Runtime. Gosched () fmt. Printf ("%c", + i) } (i)} go func () {} () waitgroup.wait ()}
Run results
Waitgroup usage examples in the Go Language Sync pack