What are non-blocking channel operations in Golang?
In Golang, channels allow communication between goroutines. By default, channel operations execute in a blocking manner.
A non-blocking channel operation is a send or receive channel operation that doesn't execute in a blocking manner. That is, it doesn't wait until another operation succeeds or the channel becomes disconnected.
To implement non-blocking channel operations in Golang, the select statement is used. We'll use Golang version 1.18.2. This is demonstrated below:
Code example
Let's look at the code below:
package mainimport "fmt"func main() {numbers := make(chan int)messages := make(chan string, 3)select {case num := <-numbers:fmt.Println("received number", num)default:fmt.Println("number not received")}msg := "hello world"select {case messages <- msg:fmt.Println("sent message", msg)default:fmt.Println("message not sent")}select {case msg := <-messages:fmt.Println("received message", msg)case num := <-numbers:fmt.Println("received number", num)default:fmt.Println("nothing happened here!")}}
Code explanation
Line 7: We define a new
intchannel with no buffer capacity.Line 8: We define a new
stringchannel with a buffer capacity of3.Lines 10–15: We use the
selectstatement to check if a number was received from the channel. In this case, none was received. Hence, the default statement is executed.Line 17: We define a
msgstring to be sent to themessageschannel.Lines 18–23: We use the
selectstatement here to check in the first case ifmsgis received by themessageschannel. In this case,msgis sent to themessageschannel successfully. Hence, the output shows that thehello worldstring is sent tomessages.Lines 25–32: We have a
selectstatement that contains multiple cases. If none of the cases is true, thedefaultstatement is executed.
Conclusion
In this Answer, we learned about non-blocking channel operations and how they can be implemented in Golang.