All goroutines are asleep while using WaitGroup

I’m exploring how to use WaitGroup to wait for all goroutines to finish. Here is my code

package main

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

func main() {
	var wg sync.WaitGroup
	wg.Add(3)

	go one(wg)
	go two(wg)
	go three(wg)

	wg.Wait()
}

func one(wg sync.WaitGroup) {
	defer wg.Done()
	time.Sleep(5 * time.Second)
	fmt.Println("One")
}

func two(wg sync.WaitGroup) {
	defer wg.Done()
	time.Sleep(7 * time.Second)
	fmt.Println("Two")
}

func three(wg sync.WaitGroup) {
	defer wg.Done()
	time.Sleep(3 * time.Second)
	fmt.Println("Three")
}

I keep getting this error “all goroutines are asleep - deadlock” after all the goroutines have printed. I’m unable to understand what’s wrong here - there are no channels involved - it’s just a simple flow. What am I missing?

You are copying the WaitGroup by value, you need to pass it by reference, using wg := new(sync.WaitGroup) is idiomatic.

3 Likes

Thank you.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.