patterngoModeratepending
Go channel patterns: fan-out, fan-in, pipeline
Viewed 0 times
channelsfan-outfan-inpipelinegoroutineconcurrency
Problem
Need to structure concurrent Go programs with proper data flow between goroutines.
Solution
Core channel patterns:
// Pipeline: chain of processing stages
func generate(nums ...int) <-chan int {
out := make(chan int)
go func() {
for _, n := range nums {
out <- n
}
close(out)
}()
return out
}
func square(in <-chan int) <-chan int {
out := make(chan int)
go func() {
for n := range in {
out <- n * n
}
close(out)
}()
return out
}
// Fan-out: multiple goroutines read from same channel
// Fan-in: merge multiple channels into one
func merge(channels ...<-chan int) <-chan int {
var wg sync.WaitGroup
out := make(chan int)
for _, ch := range channels {
wg.Add(1)
go func(c <-chan int) {
defer wg.Done()
for v := range c {
out <- v
}
}(ch)
}
go func() {
wg.Wait()
close(out)
}()
return out
}
// Usage: pipeline with fan-out/fan-in
in := generate(1, 2, 3, 4, 5)
c1 := square(in) // Fan-out
c2 := square(in)
for v := range merge(c1, c2) { // Fan-in
fmt.Println(v)
}Why
Channel patterns provide structured concurrency in Go, making it easy to reason about data flow and goroutine lifecycle.
Gotchas
- Always close channels from the sender side
- Reading from a closed channel returns zero value
- Use directional channel types (<-chan, chan<-) in function signatures
Context
Go programs with concurrent data processing
Revisions (0)
No revisions yet.