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
|
// 向 channel 里投递数据
func Provider(ch chan<- int, nums ...int) {
for _, num := range nums {
ch <- num
}
close(ch)
}
// 从 channel 里消费数据
func Consumer(ch <-chan int, done chan<- struct{}, f func(int)) {
for num := range ch {
f(num)
}
done <- struct{}{}
close(done)
}
func main() {
// 数据交换 channel
ch := make(chan int, 5)
// 控制 channel 退出
done := make(chan struct{})
go Provider(ch, 1, 2, 3, 4, 5)
go Consumer(ch, done, func(num int) {
fmt.Println(num)
time.Sleep(time.Second)
})
// 接收退出并进行超时处理
select {
case <-done:
fmt.Println("done")
case <-time.After(time.Second * 5):
fmt.Println("timeout")
}
}
|