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 main
import "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 int channel with no buffer capacity.

  • Line 8: We define a new string channel with a buffer capacity of 3.

  • Lines 10–15: We use the select statement 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 msg string to be sent to the messages channel.

  • Lines 18–23: We use the select statement here to check in the first case if msg is received by the messages channel. In this case, msg is sent to the messages channel successfully. Hence, the output shows that the hello world string is sent to messages.

  • Lines 25–32: We have a select statement that contains multiple cases. If none of the cases is true, the default statement is executed.

Conclusion

In this Answer, we learned about non-blocking channel operations and how they can be implemented in Golang.

Free Resources