@@ -16,8 +16,9 @@ type TaskManager struct {
16
16
Registry sync.Map // Registry is a map of registered tasks
17
17
Results chan interface {} // Results is the channel of results
18
18
taskHeap taskHeap // heap of tasks
19
- wg sync.WaitGroup // wg is a wait group that waits for all tasks to finish
20
19
limiter * rate.Limiter // limiter is a rate limiter that limits the number of tasks that can be executed at once
20
+ wg sync.WaitGroup // wg is a wait group that waits for all tasks to finish
21
+ mutex sync.RWMutex // mutex protects the task handling
21
22
}
22
23
23
24
// NewTaskManager creates a new task manager
@@ -47,6 +48,8 @@ func NewTaskManager(maxTasks int, tasksPerSecond float64) Service {
47
48
// RegisterTask registers a new task to the task manager
48
49
func (tm * TaskManager ) RegisterTask (tasks ... Task ) {
49
50
for _ , task := range tasks {
51
+ tm .mutex .RLock ()
52
+ defer tm .mutex .RUnlock ()
50
53
if task .IsValid () != nil {
51
54
tm .Results <- task
52
55
continue
@@ -101,6 +104,8 @@ func (tm *TaskManager) GetResults() <-chan interface{} {
101
104
102
105
// GetTask gets a task by its ID
103
106
func (tm * TaskManager ) GetTask (id uuid.UUID ) (task Task , ok bool ) {
107
+ tm .mutex .RLock ()
108
+ defer tm .mutex .RUnlock ()
104
109
t , ok := tm .Registry .Load (id )
105
110
if ! ok {
106
111
return
@@ -155,7 +160,8 @@ func (tm *TaskManager) ExecuteTask(id uuid.UUID) (interface{}, error) {
155
160
// task not found
156
161
return nil , ErrTaskNotFound
157
162
}
158
-
163
+ tm .mutex .RLock ()
164
+ defer tm .mutex .RUnlock ()
159
165
// execute the task
160
166
tm .executeTask (& task )
161
167
// drain the results channel and return the result
@@ -192,6 +198,8 @@ func (tm *TaskManager) worker(workerID int) {
192
198
193
199
// executeTask executes a task
194
200
func (tm * TaskManager ) executeTask (task * Task ) {
201
+ tm .mutex .RLock ()
202
+ defer tm .mutex .RUnlock ()
195
203
defer tm .wg .Done ()
196
204
197
205
// reserve a token from the limiter
@@ -232,6 +240,8 @@ func (tm *TaskManager) cancelTask(task *Task, reason CancelReason, notifyWG bool
232
240
if notifyWG {
233
241
defer tm .wg .Done ()
234
242
}
243
+ tm .mutex .RLock ()
244
+ defer tm .mutex .RUnlock ()
235
245
task .Cancel ()
236
246
// set the cancelled time
237
247
task .setCancelled ()
0 commit comments