-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathworkerPool.go
More file actions
132 lines (99 loc) · 2.09 KB
/
workerPool.go
File metadata and controls
132 lines (99 loc) · 2.09 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main
import (
"log"
"sync"
"time"
"github.com/google/uuid"
)
type Worker struct {
id string
n int
result int
workerPool *WorkerPool
cache *map[int]int
}
func (w *Worker) launch() {
var wg sync.WaitGroup
wg.Add(1)
t := time.Now()
go func() {
defer func() {
wg.Done()
}()
result := Fibonacci(w.n, *w.cache, &w.workerPool.mutex)
w.result = result
}()
wg.Wait()
elapsedTime := time.Since(t)
go func() {
w.workerPool.mutex.Lock()
w.workerPool.cache[w.n] = w.result
w.workerPool.mutex.Unlock()
}()
w.workerPool.quitChan <- w.id
log.Printf(
"[%v] Computing Fib(%d) :::: Time %v :::: Result %d ::::",
w.id, w.n, elapsedTime, w.result,
)
}
type WorkerPool struct {
maxWorkers int
cache map[int]int
workers map[string]*Worker
quitChan chan string
jobQueue chan int
mutex sync.RWMutex
}
func NewWorkerPool(maxWorkers int) *WorkerPool {
return &WorkerPool{
maxWorkers: maxWorkers,
workers: make(map[string]*Worker),
quitChan: make(chan string),
jobQueue: make(chan int),
cache: make(map[int]int),
mutex: sync.RWMutex{},
}
}
func (wp *WorkerPool) startNewWorker(n int) {
if wp.maxWorkers < len(wp.workers) {
go func() {
wp.jobQueue <- n
}() // Not the best option in my opinion. A refactor may be necessary.
return
}
log.Printf("[main] Starting a Worker to compute Fib(%d)", n)
worker := Worker{
id: uuid.New().String(),
n: n,
cache: &wp.cache,
workerPool: wp,
}
wp.workers[worker.id] = &worker
go worker.launch()
}
func (wp *WorkerPool) StartListen() {
for {
select {
case n := <-wp.jobQueue:
wp.startNewWorker(n)
case id := <-wp.quitChan:
log.Printf(
"[main] Deleting Worker with ID %v computing Fib(%d)",
id, wp.workers[id].n,
)
delete(wp.workers, id)
}
}
}
func Fibonacci(n int, cache map[int]int, mutex *sync.RWMutex) int {
mutex.RLock()
res, exists := cache[n]
mutex.RUnlock()
if exists {
return res
}
if n <= 1 {
return n
}
return Fibonacci(n-1, cache, mutex) + Fibonacci(n-2, cache, mutex)
}