forked from GoesToEleven/GolangTraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
69 lines (60 loc) · 2.46 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
package main
import (
"fmt"
"time"
"sync/atomic"
)
var workerID int64
var publisherID int64
func main() {
input := make(chan string)
go workerProcess(input)
go workerProcess(input)
go workerProcess(input)
go publisher(input)
go publisher(input)
go publisher(input)
go publisher(input)
time.Sleep(1 * time.Millisecond)
}
// publisher pushes data into a channel
func publisher(out chan string) {
atomic.AddInt64(&publisherID, 1)
// atomic was added after recording to fix a race condition
// discover race conditions with the -race flag
// for example: go run -race main.go
// learn about the atomic package: https://godoc.org/sync/atomic#AddInt64
thisID := atomic.LoadInt64(&publisherID)
dataID := 0
for {
dataID++
fmt.Printf("publisher %d is pushing data\n", thisID)
data := fmt.Sprintf("Data from publisher %d. Data %d", thisID, dataID)
out <- data
}
}
func workerProcess(in <-chan string) {
atomic.AddInt64(&workerID, 1)
// atomic was added after recording to fix a race condition
// discover race conditions with the -race flag
// for example: go run -race main.go
// learn about the atomic package: https://godoc.org/sync/atomic#AddInt64
thisID := atomic.LoadInt64(&workerID)
for {
fmt.Printf("%d: waiting for input...\n", thisID)
input := <-in
fmt.Printf("%d: input is: %s\n", thisID, input)
}
}
/*
CHALLENGE #1
Is this fan out?
My Answer:
Yes.
-- YES
Are we "fanning out" work? Yes. We've launched several goroutines that are simultaneously publishing a message onto our channel. The golang blog says, "Fan out means you have multiple functions reading from the same channel until that channel is closed." Here we do have multiple functions reading from the same channel. So, okay, we're fanning out.
CHALLENGE #2
Is this fan in?
No.
What is being "fanned in" here? We have launched several goroutines of the same function: workerProcess. What do those goroutines do? They are all reading from an unbuffered channel. If there was a tremendous amount of processing that each "workerProcess" func executed, then all three of the "workerProcess" funcs could be processing in parallel: pulling values off the channel and processing them. There is no "fanning in" though here. Remember what the golang blog describes fan in: "A function can read from multiple inputs and proceed until all are closed by multiplexing the input channels onto a single channel that's closed when all the inputs are closed." We don't have many channels here converging into one channel.
*/