Table of Contents
Understanding WaitGroup Basics
Basic Usage Example
Common Pitfalls and Best Practices
When to Use WaitGroup
Home Backend Development Golang How to use sync.WaitGroup in Golang

How to use sync.WaitGroup in Golang

Oct 01, 2025 am 04:27 AM
go

sync.WaitGroup is used to wait for multiple goroutines to complete, increase the count by Add, Done reduces the count, and Wait blocks until the count is zero. 2. In the example, multiple worker goroutines are started, each call Done ends, and the main function call Wait is waiting for all to complete.

How to use sync.WaitGroup in Golang

When working with concurrency in Go, you'll often need to wait for multiple goroutines to finish before proceeding. sync.WaitGroup is a synchronization primitive that helps you manage this efficiently. It's ideal when you know in advance how many goroutines you're launching and want to wait for all of them to complete.

Understanding WaitGroup Basics

A WaitGroup maintains an internal counter that starts at zero. You can increase it using Add(n) , decrease it with Done() , and block until it reaches zero using Wait() . The typical pattern is:

  • Call Add(n) before starting n goroutines
  • Each goroutine calls Done() when finished
  • Use Wait() to block until all goroutines have called Done()

Basic Usage Example

Here's a simple example showing how to use WaitGroup:

package main

import (
    "fmt"
    "sync"
    "time"
)

func worker(id int, wg *sync.WaitGroup) {
    defer wg.Done() // Ensures Done is called
    fmt.Printf("Worker %d starting\n", id)
    time.Sleep(time.Second)
    fmt.Printf("Worker %d done\n", id)
}

func main() {
    var wg sync.WaitGroup

    for i := 1; i 

In this example, we start three goroutines and wait for all of them to finish. Using defer wg.Done() ensures the counter is decremented even if the function panics.

Common Pitfalls and Best Practices

While WaitGroup is straightforward, there are a few things to watch out for:

  • Always pass the WaitGroup by pointer to goroutines — never copy it
  • Ensure every Add(n) has a corresponding n calls to Done(), or you'll deadlock
  • Avoid calling Add after Wait has been invoked in another goroutine
  • Use defer wg.Done() to prevent forgetting to call Done

If you're launching goroutines in a loop, make sure loop variables are properly captured by passing them as arguments.

When to Use WaitGroup

WaitGroup works well when you have a fixed number of tasks and just need to wait for completion. It's not suitable for cases where you need to collect results or handle cancellation. For more complex scenarios, consider using channels or context.WithCancel alongside WaitGroup.

Basically, if you're doing parallel work and just need to wait for everything to finish, sync.WaitGroup is a clean, efficient choice.

The above is the detailed content of How to use sync.WaitGroup in Golang. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

The folder or file has been opened in another program The folder or file has been opened in another program Sep 20, 2025 am 08:24 AM

When the file is occupied, first check and close the relevant programs and try to restart the computer; if it is invalid, use task manager, resource monitor or ProcessExplorer to locate the occupied process, and forcefully terminate it by ending the task or taskkill command; for prevention, you need to develop good operating habits, avoid previewing or directly operating on mobile/network drives, and keep software updated.

BTC is 'digesting future market trends ahead of time': 5 most noteworthy Bitcoin points this week BTC is 'digesting future market trends ahead of time': 5 most noteworthy Bitcoin points this week Sep 20, 2025 pm 01:39 PM

Table of Contents As traditional financial markets recover, Bitcoin volatility has risen significantly. The Fed's interest rate cut expectation has become the focus of the market. The peak of Bitcoin bull market may be "only a few weeks left". Binance has seen a large-scale buy signal. ETFs continue to absorb newly mined BTC. Bitcoin (BTC) investors are closely following market trends as crypto assets enter the Fed's key interest rate decision window. At the beginning of this week, bulls need to break through the important resistance level of $117,000 to continue their uptrend. Global attention is focused on Wednesday's Federal Reserve meeting, and it is generally predicted that it will usher in the first rate cut in 2025. A past accurate BTC price model shows that all-time highs may be born in the next few weeks. Binance Order Book reveals signs of large buying influx over the weekend. Last week, the amount of BTC purchased by institutions through ETFs reached miners

What is USDH currency? How does it work? Full analysis of Hyperliquid new stablecoin What is USDH currency? How does it work? Full analysis of Hyperliquid new stablecoin Sep 17, 2025 pm 04:39 PM

Source: Polymarket On Friday, September 5, 2025, Hyperliquid, which currently occupies an absolute leading position in decentralized derivatives exchanges, announced that it is seeking to issue a "Hyperliquid-first, consistent with Hyperliquid's interests and compliant US dollar stablecoin" and invites the team to submit proposals. The launch of the new stablecoin USDH of Hyperliquid has triggered fierce competition among market makers. Major players such as Paxos, Sky and FraxFinance have all joined the competition to issue USDH, but the lesser-known NativeMarkets is at the forefront. As adoption increases, liquidity supply

Where to find folders Where to find folders Sep 20, 2025 am 07:57 AM

The most direct way is to recall the storage location, usually in folders such as desktop, documents, downloads, etc.; if it cannot be found, you can use the system search function. File "missing" is mostly due to problems such as unattention of the saving path, name memory deviation, file hiding or cloud synchronization. Efficient management suggestions: Classify by project, time, and type, make good use of quick access, clean and archive regularly, and standardize naming. Windows search and search through File Explorer and taskbar, while macOS relies on finder and Spotlight, which is smarter and more efficient. Mastering tools and developing good habits is the key.

What is Ethereum (ETH) currency? ETH price forecast 2025-2030 What is Ethereum (ETH) currency? ETH price forecast 2025-2030 Sep 17, 2025 pm 04:42 PM

Directory What is Ethereum? Why is its prediction relevant? Highlights of ETH price related to key upgrades: Key factors affecting ETH price forecasting Network technology progress Supply and demand dynamics Institutional demand Macro background ETH forecast for 2025: What are you looking forward to? What happened in 2026 ETH forecast: Medium-term trend 2030 Ethereum forecast: Long-term outlook How do we analyze ETH price forecast Comparative conclusions of Ethereum with other major cryptocurrencies: The future of Ethereum and its price forecast How to trade Ethereum? Frequently Asked Questions What Factors Impact

Google Earth's latest version is used online_Ultra-clear 3D globe without installation Google Earth's latest version is used online_Ultra-clear 3D globe without installation Sep 16, 2025 pm 12:39 PM

The latest version of Google Earth online access is https://earth.google.com/web/, which supports global high-definition satellite images, 3D terrain, street panorama and historical image backtracking. It can operate smoothly in the browser without downloading, and can synchronize collection and custom landmarks through your account.

What is Somnia (SOMI) currency? Introduction to recent price trends and future outlook What is Somnia (SOMI) currency? Introduction to recent price trends and future outlook Sep 17, 2025 am 06:18 AM

Directory What is Somnia (SOMI)? Price performance and market trends: Short-term volatility and long-term potential Technical advantages: Why can Somnia challenge the traditional Layer1? Future Outlook: 2025-2030 Price Forecast Conclusion: Somnia's Opportunities and SEO Content Opportunities Somnia (SOMI) is a high-performance Layer1 blockchain native token launched in September 2025. It has recently attracted much attention from the market due to its price fluctuations and technological innovation. As of September 12, 2025, Gate exchange data showed that SOMI price was temporarily at $1.28, although it had a pullback from the historical high of $1.90, it was still better than the main one.

Good news: China's largest currency holding company plans to increase its position in Bitcoin through additional issuance of US$500 million in stocks Good news: China's largest currency holding company plans to increase its position in Bitcoin through additional issuance of US$500 million in stocks Sep 20, 2025 pm 01:03 PM

Key information of the catalog: NextTechnology has become the 15th largest enterprise-level Bitcoin holder in the world. Strategy has firmly ranked first in the global corporate currency holding list with 636,505 BTC. NextTechnologyHolding - China's listed company with the most Bitcoin holdings, plans to raise up to US$500 million through the public issuance of common shares to further increase its holdings in BTC and support other companies' strategic layout. Key information: NextTechnology plans to raise $500 million for financing

See all articles