Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Summary for mistake 71 #58

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1692,6 +1692,40 @@ You should have a good reason to specify a channel size other than one for buffe

To accurately use `sync.WaitGroup`, call the `Add` method before spinning up goroutines.

Calling `sync.WaitGroup.Add` method inside goroutine can lead to data race since child goroutine can run at any time in any order. There is no guarantee that main goroutine will have the correct counter to wait until it become zero.
```go
wg := sync.WaitGroup{}
var v uint64
for i := 0; i < 3; i++ {
go func() {
wg.Add(1) // incrementing the counter in an unreliable way.
atomic.AddUint64(&v, 1)
wg.Done()
}()
}
wg.Wait()
fmt.Println(v) // can print any value from 0 to 3.
```
To deterministically set the counter, the `wg.Add` should be called before spinning up the goroutine:
```go
// same code
for i := 0; i < 3; i++ {
wg.Add(1)
go func() {
atomic.AddUint64(&v, 1)
wg.Done()
}()
}
```
If we know how many goroutines we will create, we can set the counter before the loop:
```go
// same code
wg.Add(3)
for i:=0; i < 3 ; i++{
// loop body
}
```

[Source code :simple-github:](https://github.com/teivah/100-go-mistakes/tree/master/src/09-concurrency-practice/71-wait-group/main.go)

### Forgetting about `sync.Cond` (#72)
Expand Down