Search⌘ K

Channel Factory and Producer-Consumer Pattern

Explore how to use the channel factory pattern where functions return channels, and apply the producer-consumer pattern with separate goroutines producing and consuming data. Understand how to manage these patterns using for-range loops over channels and synchronization in Go concurrency.

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:

Go (1.6.2)
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 starts the function pump(). As we see from line 14, pump() returns a channel of ints, which is received in the stream variable.

Look at the header of pump() at line 14. It makes a local channel ch at line ...