CodeBlanks Logo Icon CodeBlanks

sync.WaitGroup

Learn to wait for goroutines with a WaitGroup.

sync.WaitGroup

sync.WaitGroup waits for a set of goroutines to finish. Add(n) increments the counter, each goroutine calls Done() to decrement, the main program blocks on Wait() until zero.

Pattern: wg.Add(1) first, then go func() { defer wg.Done(); ... }(). Call Add outside the goroutine; otherwise a race occurs.

WaitGroup pattern

The correct WaitGroup pattern is:

  • Call wg.Add(1) before starting the goroutine
  • Inside the goroutine defer wg.Done() as the first thing
  • In main wg.Wait() blocks until all done
  • In a loop Add(1) each iteration

If you Add inside the goroutine Wait may pass before zero and goroutines leak.

Practice Print with WaitGroup

Inside main, add a sync.WaitGroup declaration and print wg done with fmt.Println.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    wg.Add(1)
    go func() { defer wg.Done(); fmt.Println("wg tamam") }()
    wg.Wait()
}

Expected output

wg tamam

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does wg.Done() do?

  • Decrements the counter Correct answer
  • Increments the counter
  • Starts waiting
  • Kills the goroutine

Explanation: decrements the counter. Add increments, Done decrements.

2 WaitGroup usage

Question
var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.____()
    work()
}()
wg.Wait()
Answer
var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    work()
}()
wg.Wait()

Explanation: Wait is in main, Done is in the goroutine.

3 Match WaitGroup concepts

Term Meaning
Add Increment the counter
Done Decrement the counter
Wait Wait
sync.WaitGroup Tip

All lessons in Intermediate