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:
package main
import (
"fmt"
"time"
)
func valueToSend() int {
// Generate a value to send, calculated/acquired each attempt
return 0
}
func main() {
s := make(chanCaution 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3