/
multipleworkers.go
83 lines (69 loc) · 1.64 KB
/
multipleworkers.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
package main
import (
"context"
"fmt"
"log"
"math/rand"
"sync"
"github.com/guilhem/gorkers"
)
var (
count = make(map[string]int)
mut = sync.RWMutex{}
)
func main() {
ctx := context.Background()
workerOne := gorkers.NewRunner(ctx, NewWorkerOne().Work, 1000, 1000)
workerTwo := gorkers.NewRunner(ctx, NewWorkerTwo().Work, 1000, 1000).InFrom(workerOne)
if err := workerOne.Start(); err != nil {
log.Panicf("workerOne start: %v", err)
}
if err := workerTwo.Start(); err != nil {
log.Panicf("workerTwo start: %v", err)
}
for i := 0; i < 100000; i++ {
workerOne.Send(rand.Intn(100))
}
workerOne.Wait().Stop()
workerTwo.Wait().Stop()
fmt.Println("worker_one", count["worker_one"])
fmt.Println("worker_two", count["worker_two"])
fmt.Println("finished")
}
type WorkerOne struct {
}
type WorkerTwo struct {
}
func NewWorkerOne() *WorkerOne {
return &WorkerOne{}
}
func NewWorkerTwo() *WorkerTwo {
return &WorkerTwo{}
}
func (wo *WorkerOne) Work(_ context.Context, in int, out chan<- int) error {
var workerOne = "worker_one"
mut.Lock()
if val, ok := count[workerOne]; ok {
count[workerOne] = val + 1
} else {
count[workerOne] = 1
}
mut.Unlock()
total := in * 2
fmt.Println("worker1", fmt.Sprintf("%d * 2 = %d", in, total))
out <- total
return nil
}
func (wt *WorkerTwo) Work(_ context.Context, in int, out chan<- interface{}) error {
var workerTwo = "worker_two"
mut.Lock()
if val, ok := count[workerTwo]; ok {
count[workerTwo] = val + 1
} else {
count[workerTwo] = 1
}
mut.Unlock()
totalFromWorkerOne := in
fmt.Println("worker2", fmt.Sprintf("%d * 4 = %d", totalFromWorkerOne, totalFromWorkerOne*4))
return nil
}