-
Notifications
You must be signed in to change notification settings - Fork 75
/
go-channel-case-4.go
59 lines (50 loc) · 1.05 KB
/
go-channel-case-4.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
package main
import (
"fmt"
"sync"
"time"
)
type signal struct{}
func worker(i int, quit <-chan signal) {
fmt.Printf("worker %d: is working...\n", i)
LOOP:
for {
select {
default:
// 模拟worker工作
time.Sleep(1 * time.Second)
case <-quit:
break LOOP
}
}
fmt.Printf("worker %d: works done\n", i)
}
func spawnGroup(f func(int, <-chan signal), num int, groupSignal <-chan signal) <-chan signal {
c := make(chan signal)
var wg sync.WaitGroup
for i := 0; i < num; i++ {
wg.Add(1)
go func(i int) {
fmt.Printf("worker %d: start to work...\n", i)
f(i, groupSignal)
wg.Done()
}(i + 1)
}
go func() {
wg.Wait()
c <- signal(struct{}{})
}()
return c
}
func main() {
fmt.Println("start a group of workers...")
groupSignal := make(chan signal)
c := spawnGroup(worker, 5, groupSignal)
fmt.Println("the group of workers start to work...")
time.Sleep(5 * time.Second)
// 通知workers退出
fmt.Println("notify the group of workers to exit...")
close(groupSignal)
<-c
fmt.Println("the group of workers work done!")
}