Search⌘ K
AI Features

Sequencing

Explore how to implement sequencing in Go concurrency by using channels that carry channels, structuring communication between goroutines. Understand how to synchronize tasks so they wait on each other, ensuring ordered execution. This lesson demonstrates practical use of concurrency patterns to handle coordination between processes in Go.

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:

Go (1.6.2)
package main
import ( "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:

  1. There are three rounds in the competition.

  2. In each round, both partners will have to come up with their own dishes.

  3. A player cannot move on ...

svg viewer