I'm going through Go by Example: Non-Blocking Channel Operations
As far as I understand, the first select
is triggering the default
case because there are nothing in the messages
channel, and if the default
case didn't exist, we would receive a fatal error: all goroutines are asleep - deadlock!
error, right?
Well, I cannot figure out how can I trigger the second select
, specifically trigger the case messages <- msg:
As I thought, it should work opposite to the receive. So if there's a buffer for 2 messages and we send the 3rd message to the channel, it would trigger the default
clause, but the messages
channel is empty, so why in the second select does it trigger the default
clause? And how can I trigger the case messages <- msg:
clause?
why in the second select does it trigger the default clause?
Because the channel is unbuffered and there is no other go routine blocked on receiving.
how can I trigger the case messages <- msg: clause?
You can either:
Make messages
buffered
messages := make(chan string, 1)
https://play.golang.org/p/b1aO6N-dYf
Create another go routine that is blocked on receiving
go func() {
fmt.Println("Received from other go routine", <-messages)
}()
https://play.golang.org/p/Z7e1ZcO3C5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With