...

/

Channel Factory and Producer-Consumer Pattern

Channel Factory and Producer-Consumer Pattern

This lesson provides detailed concepts on the channel factory and producer-consumer pattern.

Channel factory pattern

Another common pattern in this style of programming is that, instead of passing a channel as a parameter to a goroutine, the function makes the channel and returns it (so it plays the role of a factory). Inside the function, a lambda function is called a goroutine. The following code is an implementation of this pattern:

Press + to interact
package main
import (
"fmt"
"time"
)
func main() {
stream := pump()
go suck(stream)
// the above 2 lines can be shortened to: go suck( pump() )
time.Sleep(1e9)
}
func pump() chan int {
ch := make(chan int)
go func() {
for i := 0; ; i++ {
ch <- i
}
}()
return ch
}
func suck(ch chan int) {
for {
fmt.Println(<-ch)
}
}

At line 8, the main() goroutine ...