This repository has been archived by the owner on Feb 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
multipleworkers.go
84 lines (69 loc) · 1.59 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
84
// +build ignore
package main
import (
"context"
"fmt"
"github.com/catmullet/go-workers"
"math/rand"
"sync"
)
var (
count = make(map[string]int)
mut = sync.RWMutex{}
)
func main() {
ctx := context.Background()
workerOne := workers.NewRunner(ctx, NewWorkerOne(), 1000).Start()
workerTwo := workers.NewRunner(ctx, NewWorkerTwo(), 1000).InFrom(workerOne).Start()
go func() {
for i := 0; i < 100000; i++ {
workerOne.Send(rand.Intn(100))
}
if err := workerOne.Wait(); err != nil {
fmt.Println(err)
}
}()
if err := workerTwo.Wait(); err != nil {
fmt.Println(err)
}
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() workers.Worker {
return &WorkerOne{}
}
func NewWorkerTwo() workers.Worker {
return &WorkerTwo{}
}
func (wo *WorkerOne) Work(in interface{}, out chan<- interface{}) 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.(int) * 2
fmt.Println("worker1", fmt.Sprintf("%d * 2 = %d", in.(int), total))
out <- total
return nil
}
func (wt *WorkerTwo) Work(in interface{}, 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.(int)
fmt.Println("worker2", fmt.Sprintf("%d * 4 = %d", totalFromWorkerOne, totalFromWorkerOne*4))
return nil
}