1. 程式人生 > 實用技巧 >Go by Example: Non-Blocking Channel Operations

Go by Example: Non-Blocking Channel Operations

原文: https://gobyexample.com/non-blocking-channel-operations

Basic sends and receives on channels are blocking. However, we can useselectwith adefaultclause to implementnon-blockingsends, receives, and even non-blocking multi-wayselects.

Here’s a non-blocking receive. If a value is available onmessages

thenselectwill take the<-messagescasewith that value. If not it will immediately take thedefaultcase

A non-blocking send works similarly. Heremsgcannot be sent to themessageschannel, because the channel has no buffer and there is no receiver. Therefore thedefaultcase is selected.

We can use multiplecase

s above thedefaultclause to implement a multi-way non-blocking select. Here we attempt non-blocking receives on bothmessagesandsignals.

package main

import "fmt"

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

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

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

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