


Why is wg.Add() Placement Crucial for Guaranteed Synchronization in Go?
Oct 27, 2024 pm 08:40 PMPositioning of wg.Add() for Guaranteed Synchronization
Problem
In the Go code below, the variable v is often less than expected due to an incorrect placement of wg.Add().
<code class="go">var wg sync.WaitGroup var v int32 = 0 for i := 0; i < 100; i++ { go func() { wg.Add(1) // Wrong place atomic.AddInt32(&v, 1) wg.Done() } } wg.Wait() fmt.Println(v)</code>
Solution
wg.Add() should always be called before launching the corresponding goroutine to ensure that the main goroutine blocks until all goroutines have executed wg.Done().
<code class="go">var wg sync.WaitGroup var v int32 = 0 for i := 0; i < 100; i++ { wg.Add(1) go func() { atomic.AddInt32(&v, 1) wg.Done() } } wg.Wait() fmt.Println(v)</code>
Explanation
When wg.Add() is placed inside the goroutine, it cannot guarantee that the main goroutine will block until all goroutines complete. This is because the goroutines run concurrently and the order of execution is non-deterministic.
By placing wg.Add() before the goroutine, we ensure that the main goroutine calls wg.Add() 100 times before reaching wg.Wait(). This ensures that the main goroutine blocks until all 100 goroutines have called wg.Done(), resulting in v being consistently equal to 100.
Best Practices
When using sync.WaitGroup, follow these guidelines:
- Call wg.Add() in the "original" goroutine before starting a new goroutine using go.
- Use a defer statement to call wg.Done() to ensure it is called even if the goroutine panics.
- When passing wg to other functions, pass a pointer to avoid creating copies of the wg struct.
The above is the detailed content of Why is wg.Add() Placement Crucial for Guaranteed Synchronization in Go?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go language pack import: What is the difference between underscore and without underscore?

How to implement short-term information transfer between pages in the Beego framework?

How do I write mock objects and stubs for testing in Go?

How to convert MySQL query result List into a custom structure slice in Go language?

How can I define custom type constraints for generics in Go?

How can I use tracing tools to understand the execution flow of my Go applications?

How to write files in Go language conveniently?
