Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære WaitGroups: Waiting for Goroutines | Synchronization and Best Practices
Practice
Projects
Quizzes & Challenges
Quizer
Challenges
/
Concurrency in Go

bookWaitGroups: Waiting for Goroutines

Sveip for å vise menyen

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

main.go

copy
12345678910111213141516171819202122232425
package 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:

  1. 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.
  2. Add Goroutines to the WaitGroup:

    • Before launching each goroutine, you call the Add method on the WaitGroup, passing the number 1. This tells the WaitGroup that one more goroutine will be running and needs to be tracked.
  3. Launch Goroutines:

    • You start new goroutines using the go keyword. Each goroutine performs its work independently.
  4. Mark Goroutines as Done:

    • Inside each goroutine, you call the Done method on the WaitGroup when the work is finished. This signals that the goroutine has completed its task.
  5. Wait for All Goroutines to Finish:

    • After starting all the goroutines, you call the Wait method on the WaitGroup. This blocks the main program from continuing until all goroutines have called Done and the WaitGroup counter returns to zero.

Summary:

  • The WaitGroup helps you make sure all your goroutines finish before your program exits.
  • You use Add to set the number of goroutines, Done to signal completion, and Wait to pause until everything is done.
question mark

What is the main purpose of sync.WaitGroup in Go

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 3

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 3. Kapittel 3
some-alt