1. Why goroutine do not “hold” the program
When you first start a goroutine, it feels as if you hired a tiny assistant: “Do the work, and I’ll move on.” But Go has its own sense of humor: the assistant keeps working, and you can suddenly turn off the lights in the whole office because main finished. So we need a way to wait for background work to finish — not by “eyeballing it”, not by “let’s just sleep for 100 milliseconds”, but with a clear contract.
Let’s start with a demonstration of the problem. On paper, everything looks logical: we launch printing in a goroutine — and move on.
package main
import "fmt"
func main() {
go fmt.Println("hello from goroutine")
fmt.Println("main finished")
}
In practice, you will often see only:
main finished
Because main finished, the process stopped, and the goroutine did not even get CPU time.
Sometimes a beginner adds Sleep and is happy that it “fixed” things:
package main
import (
"fmt"
"time"
)
func main() {
go fmt.Println("hello from goroutine")
time.Sleep(10 * time.Millisecond) // a hack for demonstration
fmt.Println("main finished")
}
That really can “work”, but it is like fixing a faucet with tape: the water stops flowing exactly until you blink. In concurrent code, “it worked on my laptop” is not proof of correctness. Sleep is fine as a way to illustrate the mechanics (to show that goroutines actually start), but not as a waiting mechanism.
2. What sync.WaitGroup is
When a program has several parallel (concurrent) tasks, the brain quickly gets confused: “How many are still alive? Who is already done? When can I print the result?” sync.WaitGroup is Go’s simplest answer to that everyday pain: it keeps an internal counter of “how many tasks have not finished yet” and can wait until that counter becomes zero.
The mental model is this: WaitGroup is a scoreboard saying “Tasks left: N”. You increase N when you plan work, and decrease N when a specific piece of work finishes. Then you say once: “I’ll wait until N becomes 0.”
In Go, WaitGroup lives in the sync package, so the import is always:
import "sync"
WaitGroup has three key operations. It is convenient to keep them in mind as a table:
| Method | What it does | How to read it “in plain English” |
|---|---|---|
|
increases/decreases the counter by n | “add/subtract tasks” |
|
decreases the counter by 1 | “this task is finished” |
|
blocks until the counter becomes 0 | “wait for everyone” |
An important nuance: the zero value of sync.WaitGroup is ready to use. That means you can write var wg sync.WaitGroup — and that is perfectly fine. No make, no new, no “initialization” needed.
3. The contract of Add, Done, Wait
WaitGroup looks simple, and that is true… until you start placing Add, Done, and Wait in “interesting” places. Here it is important not just to know the methods, but to keep their usage contract in mind. Otherwise you will get a hang (an eternal wait), or the program will finish too early, or you may even hit a panic from sync with a misuse message.
The main rule sounds a bit tedious, but it saves hours of life: we increase the counter with Add before starting the goroutine, and decrease it with Done inside the goroutine, making sure of that decrease with defer.
Here is the “ideal” life cycle of one task:
flowchart TD
A[main] --> B["wg.Add(1)"]
B --> C["go worker()"]
C --> D["worker: defer wg.Done()"]
D --> E[worker: does the work]
E --> F[worker finished]
F --> G[wg counter decreased]
G --> H["main: wg.Wait()"]
H --> I[main continues working]
Why must Add come before go? Because go starts work concurrently: a new goroutine may finish before you “add it to the list of things to wait for”, and then the waiting logic breaks. In modern Go this often results in an explicit “WaitGroup misuse” panic so that you do not live in illusions.
Why is it convenient to put Done via defer at the start of a goroutine? Because you may have early return, errors, branches — and you do not want one branch to forget to “check in on the scoreboard”, while Wait() then waits forever.
4. WaitGroup usage patterns
Minimal example: one goroutine
Now let’s build the canonical minimal example: one goroutine does the work, main waits.
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("work done") // work done
}()
wg.Wait()
fmt.Println("main exits") // main exits
}
Here you can clearly see the “ritual” (in a good sense): first we say “there will be 1 task” (Add(1)), then we start the goroutine, immediately put defer wg.Done() inside, and then call wg.Wait() in main.
If you mix up the order and do wg.Add(1) after go ..., at best you will get very fragile behavior, and at worst the program will panic and stop. And that is good: it is better to fail immediately than to sometimes print “work done”, sometimes not, and sometimes hang at an unexpected moment.
Several goroutines in a loop
In real programs, you usually want to launch a batch of similar tasks: process several items, prepare several report lines, compute several pieces of a result. This is where WaitGroup really shines: it can wait for a whole group.
Imagine that we have a learning app called a “task tracker” (task manager). For now we will take the data directly in code, without files and without a database — today we care about the waiting mechanism.
Let’s describe a minimal task model:
package main
type Task struct {
ID int
Title string
Done bool
}
Now we want to build report lines like:
- [ ] 1: Buy milk
- [x] 2: Fix bug
Let us assume that formatting is “kind of” expensive (for demonstration, we add a small delay based on the ID). Important: the delay is only there so you can see concurrency with your own eyes, not to “synchronize” the program.
package main
import (
"fmt"
"time"
)
func formatTaskLine(t Task) string {
time.Sleep(time.Duration(t.ID) * 10 * time.Millisecond)
mark := " "
if t.Done {
mark = "x"
}
return fmt.Sprintf("[%s] %d: %s", mark, t.ID, t.Title)
}
Now we build the report concurrently: one goroutine per task, but we write the result into a preallocated slice by index. This is an important discipline: each goroutine writes to its own “cell”, and we do not do a shared append from different goroutines.
package main
import (
"fmt"
"sync"
)
func main() {
tasks := []Task{
{ID: 1, Title: "Buy milk", Done: false},
{ID: 2, Title: "Fix bug", Done: true},
{ID: 3, Title: "Read Go docs", Done: false},
}
lines := make([]string, len(tasks))
var wg sync.WaitGroup
wg.Add(len(tasks))
for i, t := range tasks {
go func(i int, t Task) {
defer wg.Done()
lines[i] = formatTaskLine(t)
}(i, t)
}
wg.Wait()
for _, line := range lines {
fmt.Println(line)
}
}
Here you can see several strong ideas at once.
- We do wg.Add(len(tasks)) once. This reduces the chance of making a mistake and forgetting Add(1) inside the loop.
- We pass both the index and the task itself as parameters to the anonymous function. Yes, even if you have “heard that newer Go versions fixed loop variables”, this style is still very readable: it is clearly visible that the goroutine works with specific values.
- We do not print from the goroutine. We print after wg.Wait(), so the output will be stable in task order even if the goroutines finished in a mixed order.
Passing WaitGroup into functions
As the program grows, you will quickly want to move goroutine logic into a separate function: it is more readable, easier to test, and keeps main less messy. And here a very common mistake appears: passing WaitGroup by value (that is, copying it), and then wondering why Wait() hangs. WaitGroup is a struct with internal state, and it must not be blindly copied after use begins.
The correct style is to pass a pointer.
package main
import (
"fmt"
"sync"
)
func renderTask(wg *sync.WaitGroup, t Task) {
defer wg.Done()
fmt.Println("render:", t.ID) // for example: render: 2
}
func main() {
var wg sync.WaitGroup
wg.Add(1)
go renderTask(&wg, Task{ID: 1, Title: "Buy milk"})
wg.Wait()
}
Why exactly a pointer? Because wg must be one and the same counter object for all goroutines and for the code that calls Wait(). If you pass wg by value, you get a copy: the goroutine will decrement the counter in the copy, while main will wait on the counter in the original. It is like “reporting a completed task to a neighbor, not to the manager”.
What WaitGroup does not do
It is very easy to fall in love with WaitGroup and start expecting everything from it: “let it also enforce order, collect results, and defeat races.” But WaitGroup is a narrow tool: it only waits for completion.
It does not guarantee the order in which goroutines run. If you do:
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
fmt.Println("A")
}()
go func() {
defer wg.Done()
fmt.Println("B")
}()
wg.Wait()
}
It may print A and then B, or it may print B and then A. And that is not an “error” — it is normal nondeterminism of concurrent execution.
It also does not make shared memory access safe. If several goroutines modify the same variable without access discipline, WaitGroup will not save you. It will honestly wait until everyone finishes… and you will get an unpredictable result that sometimes “seems to work”. Today our task is to learn how to wait correctly; safety of shared state is a separate topic and separate thinking tools.
5. Typical mistakes when working with sync.WaitGroup
Almost all WaitGroup problems look the same: the program either hangs on Wait(), or suddenly crashes with a panic from sync, or “sometimes fails to print part of the lines”. And the most annoying part is that the mistakes are usually not in complicated logic — they are in one line that is in “the wrong place”. So it is useful to calmly go through the most common traps, so that later you can recognize them at first glance.
Mistake #1: wg.Add(1) inside the goroutine.
This is tempting: “Well, I am launching the work, let it register itself.” But that breaks the contract: Wait() may start before you increase the counter, and the runtime will rightly complain about misuse, or you will get an early exit. The correct discipline is Add in the launching code, before go.
var wg sync.WaitGroup
go func() {
wg.Add(1) // bad: Add inside the goroutine
defer wg.Done()
}()
wg.Wait()
Mistake #2: Add comes after go.
This is almost the same problem, just reversed in form: you start the goroutine and only then “add it to the waiting list”. The goroutine may finish before Add, and waiting stops being guaranteed.
Mistake #3: forgot Done() or it is not guaranteed (no defer).
This is the classic “eternal wait”: the counter never returns to zero, and Wait() blocks forever. This often happens because of an early return inside the goroutine or because of multiple branches.
A good habit is to write defer wg.Done() as the first line inside the goroutine, and then any logic after that.
Mistake #4: mismatch between the number of Add and Done calls (the counter goes negative).
If you call Done() more times than were “added”, WaitGroup gets a negative counter and panics. This usually happens when you do wg.Add(1) in one place, but accidentally call wg.Done() twice: once directly, once through defer, or you launch the same function as a worker but forget that Done is already inside.
Mistake #5: passed WaitGroup by value and copied it accidentally.
This is the trap where “everything compiles, but Wait() hangs”. If you passed wg as a parameter of type sync.WaitGroup, you made a copy.
func worker(wg sync.WaitGroup) { // bad: copy
defer wg.Done()
}
func main() {
var wg sync.WaitGroup
wg.Add(1)
go worker(wg)
wg.Wait() // may hang
}
The correct version is to accept *sync.WaitGroup and pass &wg.
GO TO FULL VERSION