Skip to content

Commit

Permalink
fix: surround cancelCtx with the mutex
Browse files Browse the repository at this point in the history
Looks like `cancelCtx` access from the different goroutines wasn't
protected.

Signed-off-by: Artem Chernyshev <[email protected]>
  • Loading branch information
Unix4ever committed Aug 15, 2022
1 parent f37da96 commit 32db7a7
Showing 1 changed file with 11 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ type PriorityLock[T Priority[T]] struct {
takeoverCh chan struct{}

mu sync.Mutex
cancelCtxMu sync.Mutex
runningPriority T
cancelCtx context.CancelFunc
}
Expand All @@ -46,11 +47,11 @@ func NewPriorityLock[T Priority[T]]() *PriorityLock[T] {
}
}

func (lock *PriorityLock[T]) getRunningPriority() T {
func (lock *PriorityLock[T]) getRunningPriority() (T, context.CancelFunc) {
lock.mu.Lock()
defer lock.mu.Unlock()

return lock.runningPriority
return lock.runningPriority, lock.cancelCtx
}

func (lock *PriorityLock[T]) setRunningPriority(seq T, cancelCtx context.CancelFunc) {
Expand All @@ -63,6 +64,9 @@ func (lock *PriorityLock[T]) setRunningPriority(seq T, cancelCtx context.CancelF
lock.cancelCtx()
}

lock.cancelCtxMu.Lock()
defer lock.cancelCtxMu.Unlock()

lock.runningPriority, lock.cancelCtx = seq, cancelCtx
}

Expand Down Expand Up @@ -92,12 +96,14 @@ func (lock *PriorityLock[T]) Lock(ctx context.Context, takeOverTimeout time.Dura
<-lock.takeoverCh
}()

if !seq.CanTakeOver(lock.getRunningPriority()) && !opts.Takeover {
sequence, cancelCtx := lock.getRunningPriority()

if !seq.CanTakeOver(sequence) && !opts.Takeover {
return nil, runtime.ErrLocked
}

if lock.cancelCtx != nil {
lock.cancelCtx()
if cancelCtx != nil {
cancelCtx()
}

select {
Expand Down

0 comments on commit 32db7a7

Please sign in to comment.