Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-blocking channel operations in go. Send?

Tags:

go

channel

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?

like image 619
Arno Avatar asked Feb 05 '23 14:02

Arno


1 Answers

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

like image 192
Tim Cooper Avatar answered Feb 21 '23 14:02

Tim Cooper