forked from betty200744/ultimate-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.go
77 lines (69 loc) · 1.38 KB
/
channel.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
package channel
import (
"context"
"fmt"
"time"
)
// for loop, exit when i >3
func Channel1() {
queue := make(chan int, 3)
for i := 0; i < 3; i++ {
queue <- i
}
for i := 0; i < 3; i++ {
fmt.Println(<-queue)
}
}
// exit for range loop by close channel
func Channel2() {
queue := make(chan int, 3)
for i := 0; i < 3; i++ {
queue <- i
}
// need close when use range, 即exit the for loop, 避免deadlock
close(queue)
for ele := range queue {
fmt.Println(ele)
}
}
// exit for while loop by ctx.Done
func Channel3() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func(ctx context.Context) {
for {
select {
case <-time.After(time.Second * 100):
// exit the select loop
case <-ctx.Done():
fmt.Println("NormalJobRun return, so exit for loop ")
return
}
}
}(ctx)
}
// receive only channel 不能 close,直接编译错误。但 send only channel 是可以被正常 close 的
func Channel4() {
sendOnly := make(chan<- int, 3)
for i := 0; i < 3; i++ {
sendOnly <- i
}
close(sendOnly)
receiveOnly := make(<-chan int, 3)
for i := 0; i < 3; i++ {
fmt.Println(<-receiveOnly)
}
//close(receiveOnly) error
}
// send to a close channel, then panic
func Channel5() {
ch := make(chan int, 0)
close(ch)
ch <- 1
}
// receive a close channel, then default value
func Channel6() {
ch := make(chan int, 0)
close(ch)
<-ch
}