WaitGroups: Waiting for Goroutines
Swipe to show menu
In this chapter, you will explore WaitGroups in Go and learn how they help you coordinate and synchronize the execution of multiple goroutines. As you build concurrent programs, you often need to ensure that several tasks finish before your program continues or completes. WaitGroups provide a simple and reliable way to accomplish this. You will see practical examples and clear explanations designed for beginners, so you can confidently apply WaitGroups in your own Go projects.
What Are WaitGroups in Go?
A WaitGroup in Go is a synchronization primitive from the sync package. It lets you wait for a collection of goroutines to complete before your program continues.
When you launch multiple goroutines to perform tasks concurrently, you often need a way to know when all those tasks are finished. A WaitGroup provides this control:
- You add the number of goroutines you want to wait for;
- Each goroutine signals when it is done;
- Your main program waits until all signals have been received.
This ensures your program does not exit or move forward until every goroutine has completed its work.
Why Use WaitGroups?
When you launch multiple goroutines, you often need to know when all of them have finished their work before moving on. WaitGroups provide a simple way to synchronize these goroutines, letting you wait for them to complete without using manual counters or complex signaling.
When to Use WaitGroups
- When you need to start several goroutines to perform tasks in parallel;
- When your main program or another goroutine must wait until all those tasks are done before continuing;
- When you want to avoid race conditions or partial results caused by goroutines finishing at unpredictable times.
How WaitGroups Work
A WaitGroup acts as a counter:
- You add to the counter with
Add(n)for the number of goroutines you plan to wait for; - Each goroutine calls
Done()when it finishes, which decrements the counter; - The main goroutine calls
Wait(), which blocks until the counter drops to zero.
This pattern ensures your program only moves forward after all goroutines have completed their work, making your concurrent code predictable and safe.
Use WaitGroups whenever you need to coordinate the completion of multiple goroutines, especially in cases where their results or side effects must be available before proceeding.
main.go
12345678910111213141516171819202122232425package main import ( "fmt" "sync" ) func worker(id int, wg *sync.WaitGroup) { defer wg.Done() // Mark this goroutine as done when the function returns fmt.Printf("Worker %d starting\n", id) // Simulate some work fmt.Printf("Worker %d done\n", id) } func main() { var wg sync.WaitGroup for i := 1; i <= 3; i++ { wg.Add(1) // Tell WaitGroup a new goroutine is starting go worker(i, &wg) } wg.Wait() // Wait for all goroutines to finish fmt.Println("All workers finished") }
Step-by-Step Explanation: Using WaitGroup to Synchronize Goroutines
The example demonstrates how to use the sync.WaitGroup type to coordinate multiple goroutines in Go. Here is how it works, step by step:
-
Create a WaitGroup:
- You start by declaring a variable of type
sync.WaitGroup. This object helps you keep track of how many goroutines are running and when they have finished.
- You start by declaring a variable of type
-
Add Goroutines to the WaitGroup:
- Before launching each goroutine, you call the
Addmethod on the WaitGroup, passing the number1. This tells the WaitGroup that one more goroutine will be running and needs to be tracked.
- Before launching each goroutine, you call the
-
Launch Goroutines:
- You start new goroutines using the
gokeyword. Each goroutine performs its work independently.
- You start new goroutines using the
-
Mark Goroutines as Done:
- Inside each goroutine, you call the
Donemethod on the WaitGroup when the work is finished. This signals that the goroutine has completed its task.
- Inside each goroutine, you call the
-
Wait for All Goroutines to Finish:
- After starting all the goroutines, you call the
Waitmethod on the WaitGroup. This blocks the main program from continuing until all goroutines have calledDoneand the WaitGroup counter returns to zero.
- After starting all the goroutines, you call the
Summary:
- The WaitGroup helps you make sure all your goroutines finish before your program exits.
- You use
Addto set the number of goroutines,Doneto signal completion, andWaitto pause until everything is done.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat