Bounded Channel Backpressure Pipeline
Use bounded channels for backpressure in Go pipelines between producer and consumer.
Code
package main
import ("context";"fmt")
func producer(ctx context.Context, out chan<- int) {
defer close(out)
for i := 0; ; i++ {
select {
case <-ctx.Done(): return
case out <- i:
}
}
}
func consumer(ctx context.Context, in <-chan int) {
for {
select {
case <-ctx.Done(): return
case v, ok := <-in:
if !ok { return }
fmt.Println(v)
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
ch := make(chan int, 10)
go producer(ctx, ch)
go consumer(ctx, ch)
}How the snippet works
Count the functions producer, consumer and main as the entire surface area of Bounded Channel Backpressure Pipeline.
The cycling part of this snippet is for i := 0; ; i++. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.
Using it
Signature: func producer(ctx context.Context, out chan<- int)
main sequences producer and consumer; executing the file runs that flow once.
Key statements
func producer(ctx context.Context, out chan<- int) {
defer close(out)
for i := 0; ; i++ {
select {
case <-ctx.Done(): return
case out <- i:
}
}
}
func consumer(ctx context.Context, in <-chan int) {
for {
select {
case <-ctx.Done(): return
case v, ok := <-in:
if !ok { return }
fmt.Println(v)
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
ch := make(chan int, 10)
go producer(ctx, ch)
go consumer(ctx, ch)
}
Interactive Tools for This Topic
FAQ
- How do you run Bounded Channel Backpressure Pipeline?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.