Skip to content

Commit 21381a1

Browse files
committed
fix: potential race in mutex map r/w
1 parent 07c6e8c commit 21381a1

File tree

1 file changed

+5
-13
lines changed

1 file changed

+5
-13
lines changed

pkg/tasker/tasker.go

+5-13
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ type Tasker struct {
4646
Log *log.Logger
4747
exprs map[string][]string
4848
tasks map[string]TaskFunc
49-
mutex map[string]uint32
49+
mutex map[string]*uint32
5050
ctxCancel context.CancelFunc
5151
wg sync.WaitGroup
5252
verbose bool
@@ -198,9 +198,9 @@ func (t *Tasker) Task(expr string, task TaskFunc, concurrent ...bool) *Tasker {
198198

199199
if !concurrent[0] {
200200
if len(t.mutex) == 0 {
201-
t.mutex = map[string]uint32{}
201+
t.mutex = make(map[string]*uint32)
202202
}
203-
t.mutex[ref] = 0
203+
t.mutex[ref] = new(uint32)
204204
}
205205

206206
return t
@@ -378,14 +378,7 @@ func (t *Tasker) runTasks(tasks map[string]TaskFunc) {
378378

379379
func (t *Tasker) canRun(ref string) bool {
380380
lock, ok := t.mutex[ref]
381-
if !ok {
382-
return true
383-
}
384-
if atomic.CompareAndSwapUint32(&lock, 0, 1) {
385-
t.mutex[ref] = 1
386-
return true
387-
}
388-
return false
381+
return !ok || atomic.CompareAndSwapUint32(lock, 0, 1)
389382
}
390383

391384
func (t *Tasker) doRun(ctx context.Context, ref string, task TaskFunc, rc chan result) {
@@ -400,8 +393,7 @@ func (t *Tasker) doRun(ctx context.Context, ref string, task TaskFunc, rc chan r
400393

401394
code, err := task(ctx)
402395
if lock, ok := t.mutex[ref]; ok {
403-
atomic.StoreUint32(&lock, 0)
404-
t.mutex[ref] = 0
396+
atomic.StoreUint32(lock, 0)
405397
}
406398

407399
rc <- result{err, ref, code}

0 commit comments

Comments
 (0)