WaitGroup and Deadlock
Waiting for many goroutines: sync.WaitGroup
Sometimes you don't need a channel to send results back; you just need to wait until every goroutine has finished. That's what sync.WaitGroup is for. It's a task counter:
import "sync"
var wg sync.WaitGroup
for _, file := range daftarFile {
wg.Add(1) // +1 tugas, panggil SEBELUM go
go func() {
defer wg.Done() // -1 tugas saat goroutine selesai
unggah(file)
}()
}
wg.Wait() // blok sampai penghitung kembali ke 0
fmt.Println("semua file terunggah")
Things to keep in mind:
- Call
wg.Addbeforego, not inside the goroutine. If you do it inside,Waitmight run first while the counter is still 0. defer wg.Done()makes sureDonegets called no matter what happens inside the function.- Don't copy a
WaitGroup. If you pass it to another function, pass a pointer (*sync.WaitGroup). - Since Go 1.22 every
foriteration gets its own loop variable, so the closure above can safely usefiledirectly. - Since Go 1.25 there's also
wg.Go(func() { ... }), which doesAdd(1),go, andDone()in one go.
Storing results without collisions
Several goroutines writing to the same variable at the same time cause a data race (covered in the Mutexes chapter). Writing to different slice indexes is safe, though, because each goroutine touches a different memory location:
hasil := make([]int, len(data))
for i, d := range data {
wg.Add(1)
go func() {
defer wg.Done()
hasil[i] = proses(d) // setiap goroutine punya indeks sendiri
}()
}
wg.Wait()
Deadlock
A deadlock happens when goroutines are waiting on each other and none of them can move forward. If every goroutine is blocked, the Go runtime detects it and stops the program:
fatal error: all goroutines are asleep - deadlock!
The most common causes:
// 1. Kirim ke channel unbuffered tanpa penerima
ch := make(chan int)
ch <- 1 // main blok selamanya
// 2. Range pada channel yang tidak pernah ditutup
for v := range ch { ... } // menunggu selamanya setelah nilai terakhir
// 3. Lupa memanggil Done, atau Add lebih banyak dari jumlah goroutine
wg.Add(2)
go func() { defer wg.Done() }()
wg.Wait() // menunggu Done kedua yang tidak pernah datang
This detector only kicks in when every goroutine is stuck. If even one other goroutine is still alive (say, a server waiting for connections), the program can hang silently with no error message. So get into the habit of asking: who sends, who receives, and who closes?
Task
A monitoring service needs to check many servers at once. Complete cekSemua(server []string, ping func(string) int) []int:
- run
ping(server[i])for every server in its own goroutine, all at the same time, - store each result in
hasil[i](results in the same order asserver), - use a
sync.WaitGroupto wait for every goroutine to finish, then returnhasil.
The hidden tests use a ping function that only answers correctly if all calls run concurrently, so calling ping one at a time in sequence won't pass.