Reputation: 10590
Note: In this question I compare two versions of code and try to understand why they produce different output. Links to running examples of the two versions on play.golang.org are FIG1 and FIG2.
I'm working through the Go Concurrency Patterns slides that Rob Pike presented at Google I/O 2012 and the example on Sequencing is a bit confusing. On Slide 29 there's an example of how to restore sequencing after multiplexing. In short, messages from multiple channels are multiplexed into a single channel and each Message structure shares a channel called "waitForIt". This channel is meant to ensure that the service that provides the messages (in the referenced example the boring service) and the client of the service are in sequence. I don't understand why, in order to have a sequencing of A-B-A-B-A-B, the client must send 2 waits over the waitForIt channel:
FIG1
for i := 0; i < 10; i++ {
msg1 := <-c
fmt.Printf("%s\n", msg1.str)
msg2 := <-c
fmt.Printf("%s\n", msg2.str)
msg1.wait <- true
msg2.wait <- true /* why is this second wait necessary? */
}
Why are two waits necessary if the Message struct is sharing the same channel? Shouldn't a single <-wait be sufficient, i.e.
FIG2
for i := 0; i < 10; i++ {
msg1 := <-c
fmt.Printf("%s\n", msg1.str)
msg2 := <-c
fmt.Printf("%s\n", msg2.str)
msg1.wait <- true
}
Yet when a single wait is used, Message 1 is repeated twice at beginning of the output and then the sequencing A-B-A-B... ensues, so that what's output is:
Message 1: Iteration 0
Message 2: Iteration 0
Message 1: Iteration 1 // Message 1 is repeated twice
Message 1: Iteration 2 // Here's the repetition
Message 2: Iteration 1
Message 1: Iteration 3
Message 2: Iteration 2
Message 1: Iteration 4
Message 2: Iteration 3
Message 1: Iteration 5
When there's two sends into the wait variable, as in FIG1, the sequencing is A-B-A-B... from the beginning:
Message 1: Iteration 0
Message 2: Iteration 0
Message 1: Iteration 1
Message 2: Iteration 1
Message 1: Iteration 2
Message 2: Iteration 2
Message 1: Iteration 3
Message 2: Iteration 3
Message 1: Iteration 4
Message 2: Iteration 4
Why is the second send into wait on the same channel required for a correct sequence?
Upvotes: 3
Views: 623
Reputation: 79
Reading the proper example [1] I guess that you already may know why you need both "wait for it".
Just in case:
You read two messages from the channel. Each message generator (goroutine inside boring) is waiting for a "wait for it". So you need to send two "wait for it", otherwise one of them will keep waiting.
If you send only one "true" through the channel then Joe receives its "wait for it" and can send a new message but Ann keeps waiting(or reversed).
I guess that at this point your program will be deadlocked. You want to read two messages, but you can receive only one (from Joe).
I have not tested it but I think so. Let me know if I'm wrong.
[1] http://talks.golang.org/2012/concurrency/support/sequenceboring.go
Upvotes: 2