-
Notifications
You must be signed in to change notification settings - Fork 21
/
worker.go
58 lines (49 loc) · 973 Bytes
/
worker.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
package gopool
import (
"time"
)
type Task func()
type Worker struct {
// pool represents a reference to the pool that owns this worker
pool *Pool
// task represents the task that the worker will execute
task chan Task
// lastUsedTime represents the last time the worker was used
lastUsedTime time.Time
}
func (w *Worker) run() {
go func() {
for task := range w.task {
if task == nil {
return
}
task()
w.pool.lock.Lock()
w.pool.workers.Push(w)
w.pool.running--
w.pool.lock.Unlock()
}
}()
}
type WorkerStack interface {
Push(w *Worker)
Pop() *Worker
Len() int
}
type workerStack struct {
workers []*Worker
}
func (ws *workerStack) Push(w *Worker) {
ws.workers = append(ws.workers, w)
}
func (ws *workerStack) Pop() *Worker {
if len(ws.workers) == 0 {
return nil
}
w := ws.workers[len(ws.workers)-1]
ws.workers = ws.workers[:len(ws.workers)-1]
return w
}
func (ws *workerStack) Len() int {
return len(ws.workers)
}