Go by Example: Non-Blocking Channel Operations

In Go, channels can also be used in a non-blocking way. This means that you can send or receive from a channel without blocking the program’s execution. The select statement can be used to manage non-blocking channel operations.

package main

import (
	"fmt"
	"time"
)

func main() {
	messages := make(chan string)
	signals := make(chan bool)

	// non-blocking receive
	select {
	case msg := <-messages:
		fmt.Println("received message", msg)
	default:
		fmt.Println("no message received")
	}

	// non-blocking send
	msg := "hi"
	select {
	case messages <- msg:
		fmt.Println("sent message", msg)
	default:
		fmt.Println("no message sent")
	}

	// multi-case non-blocking select
	select {
	case msg := <-messages:
		fmt.Println("received message", msg)
	case sig := <-signals:
		fmt.Println("received signal", sig)
	default:
		fmt.Println("no activity")
	}
}

In this example, the program uses non-blocking receives and sends with the select statement to handle channel data. The default case in each select statement is executed when there is no data available to receive or send on a channel.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *