-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
122 lines (109 loc) · 2.28 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"fmt"
"math/rand"
"runtime"
"sync"
"time"
)
func fanIn[T any, K any](done <- chan T, channels ...<-chan K) <- chan K{
fannedInchannel := make(chan K)
var wg sync.WaitGroup
transfer := func(c <- chan K){
defer wg.Done()
for i := range c{
select{
case <- done:
return
case fannedInchannel <- i:
}
}
}
for _,channel := range channels{
wg.Add(1)
go transfer(channel)
}
go func(){
wg.Wait()
close(fannedInchannel)
}()
return fannedInchannel
}
func randIntFetcher() int {
return rand.Intn(50000000)
}
func streamGenerator[T any, K any](done <-chan T, fn func() K) <-chan K {
stream := make(chan K)
go func() {
defer close(stream)
for {
select {
case <-done:
return
case stream <- fn():
}
}
}()
return stream
}
func take[T any, K any](done <-chan T, stream <-chan K, n int) <-chan K {
taken := make(chan K)
go func() {
defer close(taken)
for i := 0; i < n; i++ {
select {
case <-done:
return
case taken <- <-stream:
}
}
}()
return taken
}
func primeStreamGenerator[T any](done <-chan T, stream <-chan int) <-chan int {
primes := make(chan int)
isPrime := func(n int) bool {
for i := n - 1; i > 1; i-- {
if n%i == 0 {
return false
}
}
return true
}
go func() {
defer close(primes)
for {
select {
case <-done:
return
case num := <-stream:
if isPrime(num) {
primes <- num
}
}
}
}()
return primes
}
func main() {
t := time.Now()
done := make(chan bool)
defer close(done)
// Fan-out: Create a single source of random integers
randomIntStream := streamGenerator(done, randIntFetcher)
availableCPUs := runtime.NumCPU()
fmt.Println("available cpus are:", availableCPUs)
// Fan-out: Distribute work across multiple goroutines
// Create multiple prime finder channels, each processing the random int stream
primeFinderChannels := make([]<-chan int, availableCPUs)
for i := 0; i < availableCPUs; i++ {
primeFinderChannels[i] = primeStreamGenerator(done, randomIntStream)
}
// Fan-in: Combine results from multiple channels into a single channel
finalChannel := fanIn(done, primeFinderChannels...)
// Process the results from the combined channel
for num := range take(done, finalChannel, 10) {
fmt.Println(num)
}
fmt.Println(time.Since(t))
}