4

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?

Arno
  • 356
  • 5
  • 18

1 Answers1

9

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:

  1. Make messages buffered

    messages := make(chan string, 1)
    

    https://play.golang.org/p/b1aO6N-dYf

  2. 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

  • even more questions :D but hopefully I'll figure out it on my own, thank you! – Arno Dec 06 '16 at 16:39
  • @Arno, read this post http://stackoverflow.com/questions/18660533/why-using-unbuffered-channel-in-the-the-same-goroutine-gives-a-deadlock for the explanations :) – Jinsong Li Dec 07 '16 at 18:29