...

/

Generator Pattern

Generator Pattern

Let's study our first pattern​ of concurrency, which is about generators that return channels as returning argument.

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:

Press + to interact
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 ...

Access this course and 1400+ top-rated courses and projects.