Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: potential race in mutex map r/w #46

Merged
merged 2 commits into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading