Where Should You Place `wg.Add()` in Concurrent Go Programs?

Susan Sarandon
Release: 2024-10-26 13:28:02
Original
989 people have browsed it

 Where Should You Place `wg.Add()` in Concurrent Go Programs?

Understanding the Placement of wg.Add()

In concurrent Go programs, the sync.WaitGroup type serves as a synchronization primitive to coordinate the completion of tasks. When working with a WaitGroup, where you place the wg.Add() call is critical for ensuring proper wait behavior.

Consider the following code:

<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>
Copy after login

This code intends to parallelize a series of tasks and increment a shared variable v concurrently. However, the output often results in values less than 100. The issue lies in the placement of wg.Add(1) within the anonymous goroutine.

By placing wg.Add(1) within the goroutine, the main goroutine may resume execution before wg.Done() is called. This could occur because the concurrency model allows both the wg.Add(1) call and wg.Done() call to execute concurrently, potentially leading to premature termination of the wait in the main goroutine.

To resolve this issue, the wg.Add(1) call should be moved outside the goroutine, as shown below:

<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>
Copy after login

By moving wg.Add(1) outside the goroutine, we ensure that the main goroutine will block on the wg.Wait() call until all goroutines have completed and called wg.Done(). This guarantees that the final value of v is accurate.

As a general practice, it is recommended to always call wg.Add() before launching a goroutine that will call wg.Done(). This ensures proper wait behavior and eliminates any race conditions that may arise.

The above is the detailed content of Where Should You Place `wg.Add()` in Concurrent Go Programs?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template