-
Notifications
You must be signed in to change notification settings - Fork 0
/
five.go
80 lines (67 loc) · 1.43 KB
/
five.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
package main
import (
"fmt"
"math/rand"
"strconv"
"sync"
"time"
)
func collectLogs(wg *sync.WaitGroup, closeChan chan struct{}) (chan<- bool, <-chan map[bool]int) {
logChan := make(chan bool, 100)
resultChan := make(chan map[bool]int)
go func() {
log := make(map[bool]int)
for {
select {
case success := <-logChan:
log[success]++
wg.Done()
case <-closeChan:
resultChan <- log
return
}
}
}()
return logChan, resultChan
}
func sendMessages(logChan chan<- bool) chan<- string {
msgChan := make(chan string) // limiter will be the blocker anyway
go func() {
limiter := make(chan struct{}, 1000)
for message := range msgChan {
_ = message
limiter <- struct{}{}
go func() {
time.Sleep(100 * time.Millisecond)
if rand.Intn(10) == 0 {
logChan <- false
} else {
logChan <- true
}
<-limiter
}()
}
}()
return msgChan
}
func main() {
defer func(t time.Time) { fmt.Printf("total took %v\n", time.Since(t)) }(time.Now())
wg := new(sync.WaitGroup)
closeChan := make(chan struct{})
logChan, resultChan := collectLogs(wg, closeChan)
msgChan := sendMessages(logChan)
for _, message := range generateDummyMessages() {
wg.Add(1)
msgChan <- message
}
wg.Wait()
close(closeChan)
fmt.Println(<-resultChan)
}
func generateDummyMessages() []string {
messages := make([]string, 10000)
for i := range messages {
messages[i] = strconv.Itoa(i)
}
return messages
}