forked from jincheng9/go-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
select.go
57 lines (52 loc) · 889 Bytes
/
select.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
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"fmt"
"time"
)
func a() {
var c1, c2, c3 chan int = make(chan int), make(chan int), make(chan int)
var i1, i2 int
go func() {
c1 <- 10
i1 = <-c2
}()
for {
select {
case c2 <- i2:
print("sent ", i2, " to c2\n")
case i1 = <-c1:
fmt.Print("received ", i1, " from c1\n")
case i3, ok := (<-c3): // same as: i3, ok := <-c3
if ok {
print("received ", i3, " from c3\n")
} else {
print("c3 is closed\n")
}
default:
print("no communication\n")
}
time.Sleep(2*time.Second)
}
}
func b() {
ch1 := make(chan int, 10)
ch2 := make(chan int, 10)
go func() {
for i:=0; i<10; i++ {
ch1 <- i
ch2 <- i
}
}()
for i := 0; i < 10; i++ {
select {
case x := <-ch1:
fmt.Printf("receive %d from channel 1\n", x)
case y := <-ch2:
fmt.Printf("receive %d from channel 2\n", y)
}
}
}
func main() {
//a()
b()
}