-
Notifications
You must be signed in to change notification settings - Fork 0
/
Faninpatternperfect1.go
96 lines (59 loc) · 1.46 KB
/
Faninpatternperfect1.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
88
89
90
91
92
93
94
95
96
package main
import (
"context"
"fmt"
"sync"
)
func fanIn(ctx context.Context, fetchers ...<-chan interface{}) <-chan interface{} {
fmt.Println(" fanIn starts")
combinedFetcher := make(chan interface{})
// 1
var wg sync.WaitGroup
wg.Add(len(fetchers))
fmt.Println("3 go routines waits ")
// 2
for _, f := range fetchers {
fmt.Println(" go routines ranges", f)
f := f
go func() {
// 3
fmt.Println("unnamed go routines executes")
defer wg.Done()
for {
select {
case res := <-f:
fmt.Println(" data copied from one channel to another")
combinedFetcher <- res
case m := <-ctx.Done():
fmt.Println(" context exited goroutine", m)
return
}
}
}() //registering the 3 gorouitne
}
// 4
// Channel cleanup
fmt.Println("2nd unnamed go routines may register")
go func() {
fmt.Println(" waiting for all goroutines")
wg.Wait()
close(combinedFetcher)
fmt.Println(" waiting is over")
}()
return combinedFetcher
}
func main() {
fmt.Println(" main starts")
ctx := context.TODO()
ch1 := make(chan interface{})
ch2 := make(chan interface{})
ch3 := make(chan interface{})
ch4 := fanIn(ctx, ch1, ch2, ch3) // 4 go routines
fmt.Println(" ch1 written")
ch1 <- "coderrange"
fmt.Println(" ch2 written")
ch2 <- "glolang"
fmt.Println(" ch3 written")
ch3 <- "rust"
fmt.Println(" main ends", <-ch4)
}