I read about select statements and its execution steps but I'm not fully understanding what's happening here.
I created two examples of a Fan-In function (from the Go Concurrency Patterns talk)
select {
case value := <-g1:
c <- value
case value := <-g2:
c <- value
}
Prints from each channel as expected (each channel keeps its own counter):
Bob : 0
Alice: 0
Bob : 1
Alice: 1
Bob : 2
Alice: 2
Alice: 3
Alice: 4
Bob : 3
Alice: 5
select {
case c <- <-g1:
case c <- <-g2:
}
It is randomly selecting a channel and discarding the other one's value:
Bob : 0
Alice: 1
Alice: 2
Alice: 3
Bob : 4
Alice: 5
Bob : 6
Alice: 7
Alice: 8
Bob : 9
Update: while writing this question, I thought the second select
was equal to:
var v string
select {
case v = <-g1:
case v = <-g2:
c <- v
}
But I was wrong, because this one always prints from the second channel (as expected from a switch like statement because there isn't fallthrough in select statements):
Bob : 0
Bob : 1
Bob : 2
Bob : 3
Bob : 4
Bob : 5
Bob : 6
Bob : 7
Bob : 8
Bob : 9
Does someone understand why my second example creates a sequence?
Thanks,