Home >Backend Development >Golang >How to Efficiently Select on Buffered Send and Unbuffered Receive Channels in Go?
Go Language: Simultaneously Selecting on Buffered and Unbuffered Channels
The task at hand is to achieve simultaneous selection on a buffered send channel and an unbuffered receive channel without constantly consuming CPU resources. This scenario is equivalent to blocking until a channel is ready to send without transmitting any data.
To address this, we can employ a select statement with a default case. When neither channel is ready, the default case is triggered, initiating a brief sleep duration. This allows for resource conservation while still enabling continuous attempts to send and receive data:
<code class="go">package main import ( "fmt" "time" ) func valueToSend() int { // Generate a value to send, calculated/acquired each attempt return 0 } func main() { s := make(chan<- int, 5) r := make(<-chan int) for { v := valueToSend() // Updated value for each send attempt select { case s <- v: fmt.Println("Sent value:", v) case vr := <-r: fmt.Println("Received:", vr) default: // None of the channels are ready time.Sleep(time.Millisecond * 1) } } }</code>
Caution must be exercised when relying on channel length or capacity checks before sending or receiving data. Such approaches can lead to unexpected behavior, as the channel state can change in between the check and the actual send/receive operation.
The above is the detailed content of How to Efficiently Select on Buffered Send and Unbuffered Receive Channels in Go?. For more information, please follow other related articles on the PHP Chinese website!