Golang Concurrency #7 - WaitGroup

Just a guy who loves to write code and watch anime.
Search for a command to run...

Just a guy who loves to write code and watch anime.
No comments yet. Be the first to comment.
Qualities that make outstanding builders.

Bipedal vs quadrupedal: how many legs This is about the number of legs the creature walks on. Bipedal. Two legs. Humans, ostriches, T-rex, kangaroos, most fantasy humanoids. Quadrupedal. Four legs. Do

Intro You hear "lerp" and "smoothstep" everywhere in game dev. They sound like math jargon. They're not. Both are small tools that do the same job: smoothly move from one value to another. The problem

What is Kinematics Kinematics is the math field. It's the study of how things move without worrying about forces (which would be dynamics). FK and IK are the two branches: forward kinematics and inver

Intro Textures are usually the biggest cost in a 3D scene. Memory, bandwidth, and load time all get eaten by them. Resizing them is the obvious lever. There's more. This post is about the less obvious

WaitGroups solve the problem: "How do I wait for multiple goroutines to finish?"
func main() {
go doWork("Job 1")
go doWork("Job 2")
go doWork("Job 3")
fmt.Println("All done!") // Prints immediately, jobs still running
}
Main function exits before goroutines finish. You need to wait for them.
func main() {
go doWork("Job 1")
go doWork("Job 2")
go doWork("Job 3")
time.Sleep(5 * time.Second) // Guess how long to wait
fmt.Println("All done!")
}
What if jobs take 6 seconds? What if they take 1 second? You're either waiting too long or not long enough.
func main() {
var wg sync.WaitGroup
wg.Add(3) // "I'm expecting 3 goroutines to finish"
go doWork("Job 1", &wg)
go doWork("Job 2", &wg)
go doWork("Job 3", &wg)
wg.Wait() // Block until all 3 call Done()
fmt.Println("All done!")
}
func doWork(name string, wg *sync.WaitGroup) {
defer wg.Done() // "I'm finished" (decrements counter)
fmt.Printf("Starting %s\n", name)
time.Sleep(2 * time.Second) // Simulate work
fmt.Printf("Finished %s\n", name)
}
Add(3) sets internal counter to 3
Each Done() decrements the counter (3→2→1→0)
Wait() blocks until counter reaches 0
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(jobID int) {
defer wg.Done()
processJob(jobID)
}(i)
}
wg.Wait() // Wait for all 10 jobs
Always call Add() before starting goroutines
Always call Done() exactly once per goroutine
Use defer wg.Done() to ensure it runs even if goroutine panics
WaitGroups are like taking attendance -> you know how many people you're expecting, and you wait until everyone checks in.