// multiple producers, single consumer package main import ( "fmt" "sync" ) // producers sends the value to the channel func producers(id int, ch chan<- int, wg *sync.WaitGroup) { defer wg.Done() for i:=1; i <= 100; i++ { fmt.Printf("goroutine %d sent the value %d\n", id, i) ch <- i } } // consumers consumes the values func consumers(id int, ch <-chan int, wg *sync.WaitGroup) { defer wg.Done() for val := range ch { fmt.Printf("value received by goroutine %d: %d\n",id, val) } } func main() { ch := make(chan int) var wg sync.WaitGroup var prowg sync.WaitGroup // separate waitgroup for producers numProducers := 2 for i:=1; i <= numProducers; i++ { prowg.Add(1) go producers(i, ch, &wg) } go func () { prowg.Wait() close(ch) }() wg.Add(1) go consumers(i, ch, &wg) wg.Wait() }