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
package main

import (
"context"
"fmt"
"sync"
"time"
)

func (ctx context.Context) <-chan int {
ch := make(chan int, 64)
go func() {
defer func() {
close(ch)
}()

i := 0
for {
select {
case <-ctx.Done():
return
case <-time.After(1 * time.Second):
ch <- i
i++
}
}
}()
return ch
}

func Exec(ch <-chan int) error {
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()

v := <-ch
fmt.Println(i, v)
}(i)
}
wg.Wait()


return nil
}

// Start
// Exec
// 每个函数都是同步函数
// 遵循谁 send 谁 close
// 谁使用谁清理
// 通知-等待 模型

func main() {
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(5*time.Second, func() {
cancel()
})

ch := Start(ctx)
if err := Exec(ch); err != nil {
panic(err)
}
}