Sequencing
This lesson will teach you about a pattern used for sequencing in a program by sending channel over a channel.
We'll cover the following...
Remember the code from the last lesson where we unblock the two receive operations. Here is the code for you to recap:
Press + to interact
package mainimport ( "fmt""math/rand""time")func updatePosition(name string) <-chan string {positionChannel := make(chan string)go func() {for i := 0; ; i++ {positionChannel <- fmt.Sprintf("%s %d", name , i)time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)}}()return positionChannel}func fanIn(mychannel1, mychannel2 <-chan string) <-chan string {mychannel := make(chan string)go func() {for {mychannel <- <-mychannel1}}()go func() {for {mychannel <- <-mychannel2}}()return mychannel}func main() {positionsChannel := fanIn(updatePosition("Legolas :"), updatePosition("Gandalf :"))for i := 0; i < 10; i++ {fmt.Println(<-positionsChannel)}fmt.Println("Done with getting updates on positions.")}
What if we don’t want to block the code and introduce sequence to our program instead of randomness? Let’s see how we approach this problem.
Imagine a cooking competition. You are participating in it with your partner.
The rules of the game are:
-
There are three rounds in the competition.
-
In each round, both partners will have to come up with their own dishes.
-
A player cannot move on to the ...
Access this course and 1400+ top-rated courses and projects.