Producer–Consumer
Definition
Producer–consumer
- In plain English
- Producer–consumer is a pattern where some goroutines create work items and others process them, connected by a shared buffer.
- Think of it like
- It is like bakers filling a cooling rack while packers empty it.
Backpressure
- In plain English
- Backpressure is when a full buffer slows producers down so consumers aren't overwhelmed.
- Think of it like
- It is like a conveyor belt stopping the oven loader when the packing table is full.
Why it exists
Baggage scanners produce bursts while sorters work steadily. A short queue absorbs those bursts.
An unlimited queue can consume all available memory. A full bounded channel instead makes producers wait.
How it works
Bounded buffer
- In plain English
- A bounded buffer holds a fixed maximum number of items.
- Think of it like
- Like a cooling rack with twelve slots.
sync.Cond
- In plain English
- A sync.Cond lets goroutines wait for a condition and be woken when it may have changed — a lower-level tool than channels.
- Think of it like
- Like a bell rung when the rack has space.
Scanner 1 and Scanner 2 feed Buffer of ten, which feeds three sorters.
- Finish producers
Wait until all sends have ended.
- Close once
A coordinator on the sending side closes the jobs channel.
- Drain work
Consumers range until the closed channel is empty.
- Join consumers
Wait for every consumer before returning.
package main
import (
"fmt"
"sync"
)
func main() {
jobs := make(chan int, 10)
var producers, consumers sync.WaitGroup
for i := 0; i < 3; i++ {
consumers.Add(1)
go func() {
defer consumers.Done()
for job := range jobs {
fmt.Println("bag", job)
}
}()
}
for p := 0; p < 2; p++ {
producers.Add(1)
go func(p int) {
defer producers.Done()
for n := 0; n < 3; n++ {
jobs <- p*3 + n
}
}(p)
}
producers.Wait()
close(jobs)
consumers.Wait()
}
Channels are the usual Go bounded buffer. With sync.Cond, check the condition in a loop while holding its lock.
Examples
Absorb scanner bursts
Two scanners submit bags. Three sorters take work from a ten-item channel.
package main
import (
"fmt"
"sync"
)
func main() {
jobs := make(chan int, 10)
var producers, consumers sync.WaitGroup
for i := 0; i < 3; i++ {
consumers.Add(1)
go func() {
defer consumers.Done()
for job := range jobs {
fmt.Println("bag", job)
}
}()
}
for p := 0; p < 2; p++ {
producers.Add(1)
go func(p int) {
defer producers.Done()
for n := 0; n < 3; n++ {
jobs <- p*3 + n
}
}(p)
}
producers.Wait()
close(jobs)
consumers.Wait()
}
The small demo may never fill the buffer. Under sustained overload, sends wait until a sorter receives.
The insight
A bounded channel provides backpressure.
Drain before shutdown
One order source submits pick tasks. Five robot goroutines consume the shared queue.
package main
import (
"fmt"
"sync"
)
func main() {
jobs := make(chan int, 2)
var producers, consumers sync.WaitGroup
for i := 0; i < 5; i++ {
consumers.Add(1)
go func() {
defer consumers.Done()
for job := range jobs {
fmt.Println("pick", job)
}
}()
}
for p := 0; p < 1; p++ {
producers.Add(1)
go func(p int) {
defer producers.Done()
for n := 0; n < 3; n++ {
jobs <- p*3 + n
}
}(p)
}
producers.Wait()
close(jobs)
consumers.Wait()
}
Jobs are received once, but completion and print order can vary. Closing does not discard queued tasks.
The insight
Clean shutdown is part of the pattern.
Stop an unlimited backlog
During a rush, a slice queue grew toward two gigabytes. This reduced demo shows growth without allocating gigabytes.
package main
import (
"fmt"
)
func main() {
queue := []int{}
for upload := 0; upload < 10000; upload++ {
queue = append(queue, upload)
}
fmt.Println("queued", len(queue))
}
package main
import (
"fmt"
"sync"
)
func main() {
jobs := make(chan int, 2)
var producers, consumers sync.WaitGroup
for i := 0; i < 1; i++ {
consumers.Add(1)
go func() {
defer consumers.Done()
for job := range jobs {
fmt.Println("print", job)
}
}()
}
for p := 0; p < 1; p++ {
producers.Add(1)
go func(p int) {
defer producers.Done()
for n := 0; n < 3; n++ {
jobs <- p*3 + n
}
}(p)
}
producers.Wait()
close(jobs)
consumers.Wait()
}
The fixed queue holds at most two waiting job numbers. Uploaded file sizes still need separate limits.
The insight
An unbounded queue moves overload into memory.
Trade-offs
Pros
- Absorb short arrival bursts.
- Bound queued item count.
Cons
- A full buffer delays producers.
- Shutdown order needs care.
Use when
- Arrival and processing speeds differ.
- Several workers share one queue.
Avoid when
- A short sequential loop is sufficient.
- Waiting producers cannot be tolerated without rejection.
Quick check
Takeaways
- Producers and consumers meet at a bounded buffer.
- Full buffers slow producers through backpressure.
- Finish producers, close, drain and wait.