I try to multiplex 2 channels, A and B. A is sending with 10 milliseconds delay and B is 1 second. I use select to wait for A and B, and send the result to a fan-in channel, and then receive value in main.
package main
import (
"fmt"
"time"
)
func talk(msg string, wait_time int) <-chan string {
ch := make(chan string)
go func () {
for i:=0;i<5;i++ {
ch <- fmt.Sprintf("%s %d", msg, i)
time.Sleep(time.Duration(wait_time)*time.Millisecond)
}
}()
return ch
}
func fanIn(input1, input2 <-chan string) <-chan string {
ch := make(chan string)
go func () {
for {
select {
case t :=<-input1:
ch <- t
case t := <-input2:
ch <- t
}
}
}()
return ch
}
func main() {
ch := fanIn(talk("A", 10), talk("B", 1000))
for i:=0; i<10; i++ {
fmt.Printf("%q
", <-ch)
}
fmt.Printf("Done
")
}
This will get the correct result as shown below
"A 0"
"B 0"
"A 1"
"A 2"
"A 3"
"A 4"
"B 1"
"B 2"
"B 3"
"B 4"
Done
My question is, when I change the case statement, I got weird output. it seems some value were dropped, and of course no more value is received in fan-in channel and deadlock happened.
select {
case ch<- <-input1:
case ch<- <-input2:
}
Result is like this:
"B 0"
"A 1"
"B 2"
"A 3"
"A 4"
fatal error: all goroutines are asleep - deadlock!
Anyone has any idea of this situation?