This is a creation in Article, where the information may have evolved or changed.
Waitgroup: It is able to wait until all the Goroutine execution is complete and block the execution of the main thread until all Goroutine execution is complete.
The official description of it is as follows:
A waitgroup waits for a collection of goroutines to finish. The main goroutine calls ADD to set the number of Goroutines to wait for. Then each of the goroutines runs and calls do when finished. At the same time, Wait can is used to block until all Goroutines has finished.
Sync. Waitgroup has only 3 methods, ADD (), Done (), Wait ().
where done () is the alias of Add (-1). Simply put, using Add () adds a count, done () minus a count, the count is not 0, and the wait () is blocked from running.
The example code is as follows:
At the same time Open three co-process to request the Web page, and so on three requests are completed before continuing to wait after the work.
VAR wg sync. Waitgroup
var urls = []string{
"http://www.golang.org/",
"http://www.google.com/",
"http://www.somestupidname.com/",
}
For _, URL: = Range URLs {
Increment the Waitgroup counter.
Wg. ADD (1)
Launch a goroutine to fetch the URL.
Go func (URL string) {
Decrement the counter when the goroutine completes.
Defer WG. Done ()
Fetch the URL.
http. Get (URL)
} (URL)
}
Wait for any HTTP fetches to complete.
Wg. Wait ()
or the following test code
Used to test send Chan 10 million times and receive 10 million performance.
Package Main
Import (
"FMT"
"Sync"
"Time"
)
Const (
num = 10000000
)
Func Main () {
TestFunc ("Testchan", Testchan)
}
Func TestFunc (name string, f func ()) {
ST: = time. Now (). Unixnano ()
F ()
Fmt. Printf ("task%s cost%d \ r \ n", name, (time). Now (). Unixnano ()-st)/int64 (Time.millisecond))
}
Func Testchan () {
VAR wg sync. Waitgroup
c: = Make (Chan string)
Wg. ADD (1)
Go func () {
For _ = Range C {
}
Wg. Done ()
}()
For I: = 0; i < num; i++ {
C <-"123"
}
Close (c)
Wg. Wait ()
}
Reference:
http://www.liguosong.com/2014/05/06/golang-sync-waitgroup/