Go course

ChannelsWaitGroup and Deadlock

Go

Display

Theme

Channels · Test exercise

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.Add before go, not inside the goroutine. If you do it inside, Wait might run first while the counter is still 0.
  • defer wg.Done() makes sure Done gets 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 for iteration gets its own loop variable, so the closure above can safely use file directly.
  • Since Go 1.25 there's also wg.Go(func() { ... }), which does Add(1), go, and Done() 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 as server),
  • use a sync.WaitGroup to wait for every goroutine to finish, then return hasil.

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.

main.go
package main

import (
	"fmt"
	"sync"
)

func cekSemua(server []string, ping func(string) int) []int {
	hasil := make([]int, len(server))
	var wg sync.WaitGroup

	// TODO: untuk setiap server, wg.Add(1) lalu jalankan goroutine
	// yang mengisi hasil[i] = ping(server[i]) dan memanggil wg.Done()

	wg.Wait()
	return hasil
}

func main() {
	server := []string{"api.toko.id", "db.toko.id", "cdn.toko.id"}
	latensi := func(s string) int { return len(s) * 3 }
	fmt.Println(cekSemua(server, latensi))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)