/
ch.go
164 lines (142 loc) · 2.78 KB
/
ch.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package main
import (
"errors"
"fmt"
"os"
"time"
)
func ch() {
var ch = make(chan int)
go func(ch chan int) {
// Tip: 由于channel没有设置长度,所以是阻塞的,逐个发送
ch <- 1
ch <- 2
ch <- 3
fmt.Println("send finished")
}(ch)
for {
select {
case i := <-ch:
fmt.Println("receive", i)
case <-time.After(time.Second):
fmt.Println("time out")
os.Exit(1)
}
}
}
func chLimit() {
var ch = make(chan int)
// Tip: channel参数设置为 chan<- 和 <-chan,可以有效地防止误用发送和接收,例如这里的chan<-只能用于发送
go func(ch chan<- int) {
ch <- 1
ch <- 2
ch <- 3
fmt.Println("send finished")
}(ch)
for {
select {
case i := <-ch:
fmt.Println("receive", i)
case <-time.After(time.Second):
fmt.Println("time out")
os.Exit(1)
}
}
}
func chClose() {
var ch = make(chan int)
go func(ch chan<- int) {
ch <- 1
ch <- 2
ch <- 3
close(ch)
fmt.Println("send finished")
}(ch)
for {
select {
case i, ok := <-ch:
if ok {
fmt.Println("receive", i)
} else {
fmt.Println("channel close")
os.Exit(0)
}
case <-time.After(time.Second):
fmt.Println("time out")
os.Exit(1)
}
}
}
func chCloseErr() {
var ch = make(chan int)
go func(ch chan<- int) {
ch <- 1
ch <- 2
ch <- 3
close(ch)
fmt.Println("send finished")
}(ch)
for {
select {
// Tip: 如果这里不判断,那么i就会一直得到chan类型的默认值,如int为0,永远不会停止
case i := <-ch:
fmt.Println("receive", i)
case <-time.After(time.Second):
fmt.Println("time out")
os.Exit(1)
}
}
}
func chTask() {
var doneCh = make(chan struct{})
var errCh = make(chan error)
go func(doneCh chan<- struct{}, errCh chan<- error) {
if time.Now().Unix()%2 == 0 {
doneCh <- struct{}{}
} else {
errCh <- errors.New("unix time is an odd")
}
}(doneCh, errCh)
select {
// Tip: 这是一个常见的Goroutine处理模式,在这里监听channel结果和错误
case <-doneCh:
fmt.Println("done")
case err := <-errCh:
fmt.Println("get an error:", err)
case <-time.After(time.Second):
fmt.Println("time out")
}
}
func chBuffer() {
var ch = make(chan int, 3)
go func(ch chan int) {
// Tip: 由于设置了长度,相当于一个消息队列,这里并不会阻塞
ch <- 1
ch <- 2
ch <- 3
fmt.Println("send finished")
}(ch)
for {
select {
case i := <-ch:
fmt.Println("receive", i)
case <-time.After(time.Second):
fmt.Println("time out")
os.Exit(1)
}
}
}
func chBufferRange() {
var ch = make(chan int, 3)
go func(ch chan int) {
// Tip: 由于设置了长度,相当于一个消息队列,这里并不会阻塞
ch <- 1
ch <- 2
ch <- 3
close(ch)
fmt.Println("send finished")
}(ch)
for i := range ch {
fmt.Println("receive", i)
}
}