翻译自 https://gobyexample.com/
Go by Example
Go is an open source programming language designed for building simple, fast, and reliable software.
Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below.
Go by Example: Non-Blocking Channel Operations
普通管道的发送与接收都是阻塞的,然而我们可以使用select的default条件来实现非阻塞的发送,接收和甚至是非阻塞的多路复用的selects
。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| package main
import "fmt"
func main() { messages := make(chan string) signals := make(chan bool)
select { case msg := <-messages: fmt.Println("recieved 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("recieved messages", msg) case sig := <-signals: fmt.Println("recieved signals", sig) default: fmt.Println("no activity") } }
|
1 2 3 4
| tashuo:golang ta_shuo$ go run non-blocking-channel.go no message received no message sent no activity
|
原文链接:Go by Example: Non-Blocking Channel Operations