WaitGroup Demo

Coordinate multiple goroutines and wait for all to finish.

package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	var wg sync.WaitGroup

	for i := 1; i <= 5; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			time.Sleep(time.Duration(id*100) * time.Millisecond) // simulate work
			fmt.Printf("worker %d done\n", id)
		}(i)
	}

	wg.Wait()
	fmt.Println("all workers finished")
}
▶ Open Go Playground

Copy the code above and paste to run

© 2026 ByteLearn.dev. Free courses for developers. · Privacy