-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtaskqueue.go
More file actions
109 lines (88 loc) · 1.9 KB
/
taskqueue.go
File metadata and controls
109 lines (88 loc) · 1.9 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
package pool
import (
"fmt"
"sync"
"time"
)
type WorkerTaskQueue struct {
lock sync.Mutex
elements map[int]*WorkerTask
comm chan int
quit chan interface{}
}
func NewWorkerTaskQueue() *WorkerTaskQueue {
return &WorkerTaskQueue{
lock: sync.Mutex{},
elements: make(map[int]*WorkerTask),
comm: make(chan int),
quit: make(chan interface{}),
}
}
func (wtq *WorkerTaskQueue) getTaskWithState(id int) (*WorkerTask, error) {
wtq.lock.Lock()
defer wtq.lock.Unlock()
task, ok := wtq.elements[id]
if !ok {
return nil, fmt.Errorf("Element %d not found", id)
}
task_status := task.getStatus()
if task_status == Finished || task_status == Error {
task.setStatusChan(nil)
// Lock already here
delete(wtq.elements, id)
return task, nil
}
return nil, nil
}
func (wtq *WorkerTaskQueue) TaimedWaitTaskFinished(timeout time.Duration) (*WorkerTask, error) {
for {
select {
case id := <-wtq.comm:
task, err := wtq.getTaskWithState(id)
if task != nil || err != nil {
return task, err
}
case <-time.After(timeout):
return nil, fmt.Errorf("timeout")
case <-wtq.quit:
return nil, nil
}
}
// Unreachable
//return nil, nil
}
func (wtq *WorkerTaskQueue) WaitTaskFinished() (*WorkerTask, error) {
Loop:
for {
select {
case id := <-wtq.comm:
task, err := wtq.getTaskWithState(id)
if task != nil || err != nil {
return task, err
}
case <-wtq.quit:
break Loop
}
}
return nil, nil
}
func (wtq *WorkerTaskQueue) AddTask(wt *WorkerTask) bool {
wtq.lock.Lock()
defer wtq.lock.Unlock()
var ok bool
if _, ok = wtq.elements[wt.id]; !ok {
wtq.elements[wt.id] = wt
wt.setStatusChan(&wtq.comm)
}
return !ok
}
func (wtq *WorkerTaskQueue) RemoveTask(wt *WorkerTask) bool {
wtq.lock.Lock()
defer wtq.lock.Unlock()
var ok bool
if _, ok = wtq.elements[wt.id]; ok {
delete(wtq.elements, wt.id)
wt.setStatusChan(nil)
}
return ok
}