-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
87 lines (79 loc) · 1.49 KB
/
main.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
78
79
80
81
82
83
84
85
86
87
package main
import (
"context"
"fmt"
"sync"
"time"
)
func appleReader(ctx context.Context, parentWg *sync.WaitGroup, appleStream chan any) {
defer parentWg.Done()
var wg sync.WaitGroup
newCtx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
doWork := func(id int){
defer wg.Done()
for{
select{
case <- newCtx.Done():
return
case v, ok := <- appleStream:
if(!ok){
fmt.Println("Apple stream closed")
return
}
time.Sleep(time.Second)
fmt.Println(v, id)
}
}
}
for i:= 0; i<3; i++{
wg.Add(1)
go doWork(i)
}
wg.Wait()
}
func genericReader(ctx context.Context, wg *sync.WaitGroup, stream chan any){
defer wg.Done()
for{
select{
case <- ctx.Done():
return
case v, ok := <- stream:
if(!ok){
fmt.Println("Stream closed")
return
}
time.Sleep(time.Second)
fmt.Println(v)
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
appleStream := make(chan any)
orangeStream := make(chan any)
peachStream := make(chan any)
generator := func(data string, c chan any) {
for {
select {
case <- ctx.Done():
return
case c <- data:
}
}
}
go generator("apple", appleStream)
go generator("orange", orangeStream)
go generator("peach", peachStream)
var wg sync.WaitGroup
func () {
wg.Add(1)
go appleReader(ctx, &wg, appleStream)
wg.Add(1)
go genericReader(ctx, &wg, orangeStream)
wg.Add(1)
go genericReader(ctx, &wg, peachStream)
}()
wg.Wait()
}