Go: Common Deadlocks I | Solution 1

Since the channel was never closed the for loop in the goroutines loops forever thus no wg.Done is called thus two goroutines are waiting for new values and the third goroutine is waiting in wg.Wait() thus all goroutines are waiting/asleep thus boom! You need to close the channel!

package main

import (
	"fmt"
	"sync"
)

func main() {
	var wg sync.WaitGroup

	ch := make(chan int)

	wg.Add(2)

	go func() {

		for v := range ch {
			fmt.Println(v)
		}
		wg.Done()
	}()

	go func() {
		for v := range ch {
			fmt.Println(v)
		}
		wg.Done()
	}()

	for i := 0; i < 10; i++ {
		ch <- i
	}
	
	close(ch)

	wg.Wait()
}