Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

select non-blocking read/write operations

I’m trying to understand the behaviour of the write to channel operation in the first select in the code below:

func main() {
    ch := make(chan int)

    select {
    case ch <- 42:
        fmt.Println("Sent value to channel")
    default:
        fmt.Println("Channel is not ready for sending")
    }

    select {
    case value := <-ch:
        fmt.Println("Received value from channel:", value)
    default:
        fmt.Println("Channel is not ready for receiving")
    }
}

Does the write ch <- 42 get completed and then since there is no other goroutine to read it, the default is selected? Or, the write is never attempted since there is no goroutine to read it and default is selected?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When select statement runs, it checks to see which cases can run, and selects one randomly. If none are available to run and a default is present, default case is selected.

So in your first select statement, the channel send operation cannot run, because the channel is not buffered and there are no goroutines waiting to receive the value. Because of that, default case is selected. Similarly for the second select, because the receive operation cannot be performed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading