Search⌘ K

Generator Pattern

Explore how to implement the generator pattern in Go to create concurrent programs that produce sequences on-the-fly using channels and goroutines. Understand how this pattern allows simultaneous computation and data consumption, improving efficiency in your concurrent applications.

We'll cover the following...

In this chapter, we’ll look at some concurrency patterns that can come in handy while we write concurrent code.

Let’s begin with generators. Generators return the next value in a sequence each time they are called. This means that each value is available as an output before the generator computes the next value. Hence, this pattern is used to introduce parallelism in our program.

Have a look at the simple example below:

Go (1.6.2)
package main
import (
"fmt"
)
func foo() <-chan string {
mychannel := make(chan string)
go func() {
for i := 0; ; i++ {
mychannel <- fmt.Sprintf("%s %d", "Counter at : ", i)
}
}()
return mychannel // returns the channel as returning argument
}
func main() {
mychannel := foo() // foo() returns a channel.
for i := 0; i < 5; i++ {
fmt.Printf("%q\n", <-mychannel)
}
fmt.Println("Done with Counter")
}

In the code above, we use a generator as a function which returns a channel. The foo() function, when invoked on line 20, calls a goroutine which sends a ...