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

Write summary for mistake 71 #86

Merged
merged 1 commit into from
Oct 27, 2024
Merged
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
18 changes: 18 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1926,6 +1926,24 @@ In summary, we have to be careful with the boundaries of a mutex lock. In this s

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

The `Add` method of `sync.WaitGroup` is used to increment an internal counter of goroutines that the program should wait for. Therefore, it is important to call `Add` before starting the goroutine. If you start the goroutine before calling `Add`, there is a possibility that the goroutine will finish before `Add` is called, which may lead to an incorrect wait state.

```go
var wg sync.WaitGroup

for i := 0; i < 5; i++ {
wg.Add(1) // Adds to counter before starting goroutine
go func(i int) {
defer wg.Done() // Decrease the counter when the goroutine ends
fmt.Println(i)
}(i)
}

wg.Wait() // Wait until all goroutines finish
```

In this example, `wg.Add(1)` is called before each goroutine is started, ensuring the counter is correct. When each goroutine finishes, it calls `wg.Done()` to decrement the counter. Finally, `wg.Wait()` is used to block until all goroutines have finished. This ensures that the main program does not terminate before all goroutines have completed their work.

[:simple-github: Source code](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