Skip to content

Commit

Permalink
Merge pull request #46 from adhocore/mutex-map-race
Browse files Browse the repository at this point in the history
fix: potential race in mutex map r/w
  • Loading branch information
adhocore authored Oct 22, 2024
2 parents 07c6e8c + 2ae940a commit 89f74f2
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 14 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test-action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ jobs:
test:
strategy:
matrix:
go-version: [1.13.x, 1.14.x, 1.15.x, 1.16.x, 1.17.x, 1.18.x, 1.19.x, 1.20.x]
go-version: [1.16.x, 1.17.x, 1.18.x, 1.19.x, 1.20.x, 1.21.x, 1.22.x, 1.23.x]
os: [ubuntu-latest]
runs-on: ${{ matrix.os }}
steps:
Expand Down
18 changes: 5 additions & 13 deletions pkg/tasker/tasker.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ type Tasker struct {
Log *log.Logger
exprs map[string][]string
tasks map[string]TaskFunc
mutex map[string]uint32
mutex map[string]*uint32
ctxCancel context.CancelFunc
wg sync.WaitGroup
verbose bool
Expand Down Expand Up @@ -198,9 +198,9 @@ func (t *Tasker) Task(expr string, task TaskFunc, concurrent ...bool) *Tasker {

if !concurrent[0] {
if len(t.mutex) == 0 {
t.mutex = map[string]uint32{}
t.mutex = make(map[string]*uint32)
}
t.mutex[ref] = 0
t.mutex[ref] = new(uint32)
}

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

func (t *Tasker) canRun(ref string) bool {
lock, ok := t.mutex[ref]
if !ok {
return true
}
if atomic.CompareAndSwapUint32(&lock, 0, 1) {
t.mutex[ref] = 1
return true
}
return false
return !ok || atomic.CompareAndSwapUint32(lock, 0, 1)
}

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

code, err := task(ctx)
if lock, ok := t.mutex[ref]; ok {
atomic.StoreUint32(&lock, 0)
t.mutex[ref] = 0
atomic.StoreUint32(lock, 0)
}

rc <- result{err, ref, code}
Expand Down

0 comments on commit 89f74f2

Please sign in to comment.