8000 van sickle fan out fan in · Abhicodeitout/GolangTraining@9014e36 · GitHub
[go: up one dir, main page]

Skip to content

Commit 9014e36

Browse files
committed
van sickle fan out fan in
1 parent f17a280 commit 9014e36

File tree

1 file changed

+70
-0
lines changed
  • 22_go-routines/13_channels_fan-out_fan-in/10_van-sickle_fan-out_fan-in

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
func main() {
8+
9+
in := gen()
10+
out := make(chan int)
11+
12+
// FAN OUT
13+
// Multiple functions reading from the same channel until that channel is closed
14+
// Distribute work across multiple functions (ten goroutines) that all read from in.
15+
fanOut(in, 10, out)
16+
17+
// FAN IN
18+
// multiplex multiple channels onto a single channel
19+
// merge the channels from c0 through c9 onto a single channel
20+
go func() {
21+
for v := range out {
22+
fmt.Println(v)
23+
}
24+
}()
25+
26+
var a string
27+
fmt.Scanln(&a)
28+
}
29+
30+
func gen() <-chan int {
31+
out := make(chan int)
32+
go func() {
33+
for i := 0; i < 10; i++ {
34+
for j := 3; j < 13; j++ {
35+
out <- j
36+
}
37+
}
38+
close(out)
39+
}()
40+
return out
41+
}
42+
43+
func fanOut(in <-chan int, n int, out chan<- int) {
44+
for i := 0; i < n; i++ {
45+
factorial(in, out)
46+
}
47+
}
48+
49+
func factorial(in <-chan int, out chan<- int) {
50+
go func() {
51+
for n := range in {
52+
53+
out <- fact(n)
54+
}
55+
}()
56+
}
57+
58+
func fact(n int) int {
59+
total := 1
60+
for i := n; i > 0; i-- {
61+
total *= i
62+
}
63+
return total
64+
}
65+
66+
/*
67+
This code was provided by my friend, Mike Van Sickle
68+
He is an awesome programmer, an awesome Go programmer, and an awesome teacher
69+
Check out his courses on pluralsight to learn more about Go!
70+
*/

0 commit comments

Comments
 (0)
0