Bounded Channel Backpressure Pipeline

Use bounded channels for backpressure in Go pipelines between producer and consumer.

GoResilience

Code

snippet
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)
}