Skip to content

Commit 34d67f6

Browse files
committed
Add use-sync-waitgroup-to-synchronize-goroutines.md.
1 parent f98ed80 commit 34d67f6

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

SUMMARY.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,5 @@
4040
* [nil channel VS closed channel](posts/nil-channel-vs-closed-channel.md)
4141
* [Select operation](posts/select-operation.md)
4242
* [Need not close every channel](posts/need-not-close-every-channel.md)
43-
* [Processing JSON object](posts/processing-json-object.md)
43+
* [Processing JSON object](posts/processing-json-object.md)
44+
* [Use sync.WaitGroup to synchronize goroutines](posts/use-sync-waitgroup-to-synchronize-goroutines.md)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Use sync.WaitGroup to synchronize goroutines
2+
----
3+
[sync.WaitGroup](https://golang.org/pkg/sync/#WaitGroup) provides a goroutine synchronization mechanism, and used for waiting for a collection of goroutines to finish. In the internal of `sync.WaitGroup` struct, there is a `counter` which records how many goroutines need to be waited are living now.
4+
5+
`sync.WaitGroup` provides `3` methods: `Add`, `Done` and `Wait`. `Add` method is used to identify how many goroutines need to be waited, and it will add `counter` value. When a goroutine exits, it must call `Done`, and it will decrease `counter` value by `1`. The `main` goroutine blocks on `Wait`, once the `counter` becomes `0`, the `Wait` will return, and main goroutine can continue to run.
6+
7+
Let’s see an example:
8+
9+
package main
10+
11+
import (
12+
"sync"
13+
"time"
14+
"fmt"
15+
)
16+
17+
func sleepFun(sec time.Duration, wg *sync.WaitGroup) {
18+
defer wg.Done()
19+
time.Sleep(sec * time.Second)
20+
fmt.Println("goroutine exit")
21+
}
22+
23+
func main() {
24+
var wg sync.WaitGroup
25+
26+
wg.Add(2)
27+
go sleepFun(1, &wg)
28+
go sleepFun(3, &wg)
29+
wg.Wait()
30+
fmt.Println("Main goroutine exit")
31+
32+
}
33+
Because the `main` goroutine need to wait `2` goroutines, so the argument for `wg.Add` is `2`. The execution result is like this:
34+
35+
goroutine exit
36+
goroutine exit
37+
Main goroutine exit
38+
Please notice, the `Add` must go ahead of `Done`.
39+
40+
Reference:
41+
[Use sync.WaitGroup in Golang](http://nanxiao.me/en/use-sync-waitgroup-in-golang/).

0 commit comments

Comments
 (0)