How to Build a Producer-Consumer System in Go

Build a Go producer-consumer system using buffered channels to safely pass data between goroutines.

Use a buffered channel to decouple a producer goroutine from a consumer goroutine.

package main

import "fmt"

func main() {
    jobs := make(chan int, 5)
    results := make(chan int, 5)

    go func() {
        for j := 1; j <= 3; j++ {
            jobs <- j
        }
        close(jobs)
    }()

    go func() {
        for j := range jobs {
            results <- j * 2
        }
        close(results)
    }()

    for r := range results {
        fmt.Println(r)
    }
}