-
Notifications
You must be signed in to change notification settings - Fork 0
/
non-blocking.go
46 lines (40 loc) · 1.25 KB
/
non-blocking.go
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
38
39
40
41
42
43
44
45
46
package main
import "fmt"
/*
Basic sends and receives on channels are blocking. However, we can use select with a default
clause to implement non-blocking sends, receives, and even non-blocking multi-way selects.
*/
func main() {
messages := make(chan string)
signals := make(chan bool)
// Here’s a non-blocking receive. If a value is available on messages then select will
// take the <-messages case with that value. If not it will immediately take the default case.
select {
case msg := <-messages:
fmt.Println("received message", msg)
default:
fmt.Println("no message received")
}
/*
A non-blocking send works similarly. Here msg cannot be sent to the messages channel,
because the channel has no buffer and there is no receiver. Therefore the default case
is selected.
*/
msg := "hi"
select {
case messages <- msg:
fmt.Println("sent message", msg)
default:
fmt.Println("no message sent")
}
// We can use multiple cases above the default clause to implement a multi-way
// non-blocking select. Here we attempt non-blocking receives on both messages and signals.
select {
case msg := <-messages:
fmt.Println("received message", msg)
case sig := <-signals:
fmt.Println("received signal", sig)
default:
fmt.Println("no activity")
}
}