Home >Backend Development >Golang >Where Should You Place `wg.Add()` for Accurate Counting in Go\'s `sync.WaitGroup`?

Where Should You Place `wg.Add()` for Accurate Counting in Go\'s `sync.WaitGroup`?

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 07:15:30195browse

  Where Should You Place `wg.Add()` for Accurate Counting in Go's `sync.WaitGroup`?

Wait Group Placement for Accurate Counting

In concurrent programming, the sync.WaitGroup type serves as a synchronization primitive for coordinating goroutines. It tracks the number of tasks that need to complete before a blocking call to wg.Wait() can proceed.

Proper Placement of wg.Add()

To ensure accurate task counting, it's crucial to call wg.Add(1) before launching a goroutine that subsequently calls wg.Done(). This placement guarantees that the main goroutine will block at wg.Wait() until all launched goroutines have completed.

Alternate Placement Consequences

As demonstrated in the example code, placing wg.Add(1) within the goroutine can lead to premature completion of wg.Wait(). This occurs because, within the same goroutine, wg.Done() is called immediately after wg.Add(1), causing the main goroutine to resume execution before all tasks are finished.

Deterministic Completion

When wg.Add() is correctly placed before the goroutine launches, the main goroutine cannot reach wg.Wait() until after the for loop. This ensures that wg.Add() is called exactly 100 times, and thus wg.Wait() blocks until wg.Done() is called 100 times.

Alternatives

As an alternative, if the number of loop iterations is known in advance, wg.Add(100) can be called before the loop. However, this approach should be used with caution, as it assumes no conditional skipping within the loop.

Best Practices

For consistent and reliable usage of sync.WaitGroup, follow these guidelines:

  1. Call wg.Add() in the main goroutine before starting a new goroutine.
  2. Call wg.Done() deferred in the goroutine to ensure completion even in case of panics.
  3. When sharing a WaitGroup between functions, pass a pointer to the WaitGroup to avoid making copies.

The above is the detailed content of Where Should You Place `wg.Add()` for Accurate Counting in Go\'s `sync.WaitGroup`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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