Producer Consumer

Multiple producers, multiple consumers, clean shutdown with channel close.

package main

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

func producer(id int, ch chan<- string, wg *sync.WaitGroup) {
	defer wg.Done()
	for i := 0; i < 3; i++ {
		msg := fmt.Sprintf("p%d-item%d", id, i)
		ch <- msg
		fmt.Println("produced:", msg)
		time.Sleep(50 * time.Millisecond) // simulate production delay
	}
}

func consumer(id int, ch <-chan string, wg *sync.WaitGroup) {
	defer wg.Done()
	for msg := range ch {
		fmt.Printf("consumer %d got: %s\n", id, msg)
		time.Sleep(100 * time.Millisecond) // simulate processing time
	}
	fmt.Printf("consumer %d done\n", id)
}

func main() {
	ch := make(chan string, 5)

	var producers sync.WaitGroup
	for i := 1; i <= 3; i++ {
		producers.Add(1)
		go producer(i, ch, &producers)
	}

	var consumers sync.WaitGroup
	for i := 1; i <= 2; i++ {
		consumers.Add(1)
		go consumer(i, ch, &consumers)
	}

	// Close channel after all producers finish
	go func() {
		producers.Wait()
		close(ch)
	}()

	consumers.Wait()
	fmt.Println("all done")
}
▶ Open Go Playground

Copy the code above and paste to run

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