-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path030.Goroutine_Channel_Select_behavieor.go
55 lines (49 loc) · 1.33 KB
/
030.Goroutine_Channel_Select_behavieor.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
package main
import (
"fmt"
)
func main() {
DemoSelectIsRandomToEashCase()
}
func DemoSelectIsRandomToEashCase() {
//優先順序
// Closed Channel > default > Open Channel
// c1, c2 close 之前,會先跑 default
// c1, c2 close 之後,剩下就只跑 c1, c2 次數會隨機平分。
// 書上有一句描述很傳神:「Go 語言 runtime 無法解析 select 的意圖」
var CloseChannels = func(channels ...chan interface{}) {
for _, channel := range channels {
close(channel)
}
}
c1 := make(chan interface{})
c2 := make(chan interface{})
// CloseChannels(c2)
var c1Count, c2Count, defaultCount int
//defer fmt.Printf("c1Count:%d, c2Count:%d, defaultCount:%d\n", c1Count, c2Count, defaultCount)
fmt.Println("Into for loop")
for i := 1; i < 1000; i++ {
select {
case <-c1:
c1Count++
// if 600 == i {
// // CloseChannels(c1, c2)
// }
case <-c2:
c2Count++
// if 600 == i {
// // CloseChannels(c1, c2)
// }
default:
// 若其他 channel 都尚未關閉,就會跳到這裡來
defaultCount++
if 600 == i {
CloseChannels(c1, c2)
fmt.Printf("c1Count:%d, c2Count:%d, defaultCount:%d. ", c1Count, c2Count, defaultCount)
fmt.Printf("c1 and c2 closed\n")
}
}
}
// CloseChannels(c1, c2)
fmt.Printf("c1Count:%d, c2Count:%d, defaultCount:%d\n", c1Count, c2Count, defaultCount)
}