This is a creation in Article, where the information may have evolved or changed.
The-waitgroup of Golang study notes
After graduating from work, because of limited time, once interrupted the writing study notes.
Recent whim, stroll csdn found blog has been revised, added to the markdown grammar support. In addition to the recent Go language learning Google, so want to borrow blogging opportunities to learn markdown language, while combing the learning of the go language knowledge.
This article explains the use of waitgroup in the Go Standard library sync.
The role of Waitgroup
Waitgroup is used for Goroutine synchronization, Waitgroup is required when the current thread of execution needs to be blocked, waiting for a set of Goroutine to execute before continuing with the current threads.
Definition of Waitgroup
typestruct { [12]byte sema uint32}
The definition of Waitgroup is relatively simple, consisting of a 12-byte state1 field and a 32-bit sema .
Waitgroup's API
1.Add(delta int)
The prototype of add is declared as follows:
funcint)
The Add function accepts a int
type of parameter Delta, which is used to set the counter of the Waitgroup instance (WG), and when the counter becomes 0 o'clock, all of the goroutine that are blocked because the WG is raised with wait will be awakened.
If the call to add causes the counter to become negative, it causes panic.
2.Done()
The done prototype declaration is as follows:
func (wg *WaitGroup) Done()
The done function is simple, which is to subtract one of the WG's counters. This function is equivalent to wg.Add(-1)
, from the Go source code can see done () is the WG. ADD (-1) is implemented.
// Done decrements the WaitGroup counter.func (wg *WaitGroup) Done() { wg.Add(-1)}
3.Wait()
The prototype of wait is declared as follows:
func (wg *WaitGroup) Wait()
Wait blocks the goroutine that calls the function until the WG's counter changes to 1.
The use of Waitgroup
package mainimport ( "fmt" "sync")func main() { var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) gofuncint){ fmt.Println("Hello world",i) wg.Done() }(i) } wg.Wait()}
The program starts with 10 Goroutine, and is used in the main
function to wg.Wait
wait for these goroutine to finish executing. The output of the program is as follows:
Hello world 9Hello world 2Hello world 3Hello world 4Hello world 5Hello world 6Hello world 7Hello world 0Hello world 8Hello world 1
If wg
you remove the use in the sample code, no information is output because the main
function ends before the goroutine executes.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.