Skip to content

Commit

Permalink
fix: race condition in lockMap
Browse files Browse the repository at this point in the history
(cherry picked from commit afc4cb3)
  • Loading branch information
andyzhangx authored and nilo19 committed Feb 9, 2023
1 parent 4f18ef8 commit d6fb940
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 18 deletions.
26 changes: 8 additions & 18 deletions pkg/provider/azure_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,35 +56,25 @@ func newLockMap() *lockMap {
func (lm *lockMap) LockEntry(entry string) {
lm.Lock()
// check if entry does not exists, then add entry
if _, exists := lm.mutexMap[entry]; !exists {
lm.addEntry(entry)
mutex, exists := lm.mutexMap[entry]
if !exists {
mutex = &sync.Mutex{}
lm.mutexMap[entry] = mutex
}

lm.Unlock()
lm.lockEntry(entry)
mutex.Lock()
}

// UnlockEntry release the lock associated with the specific entry
func (lm *lockMap) UnlockEntry(entry string) {
lm.Lock()
defer lm.Unlock()

if _, exists := lm.mutexMap[entry]; !exists {
mutex, exists := lm.mutexMap[entry]
if !exists {
return
}
lm.unlockEntry(entry)
}

func (lm *lockMap) addEntry(entry string) {
lm.mutexMap[entry] = &sync.Mutex{}
}

func (lm *lockMap) lockEntry(entry string) {
lm.mutexMap[entry].Lock()
}

func (lm *lockMap) unlockEntry(entry string) {
lm.mutexMap[entry].Unlock()
mutex.Unlock()
}

func getContextWithCancel() (context.Context, context.CancelFunc) {
Expand Down
7 changes: 7 additions & 0 deletions pkg/provider/azure_vmss_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2636,6 +2636,13 @@ func TestEnsureBackendPoolDeleted(t *testing.T) {
}
}

func TestEnsureBackendPoolDeletedConcurrentlyLoop(t *testing.T) {
// run TestEnsureBackendPoolDeletedConcurrently 20 times to detect race conditions
for i := 0; i < 20; i++ {
TestEnsureBackendPoolDeletedConcurrently(t)
}
}

func TestEnsureBackendPoolDeletedConcurrently(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
Expand Down

0 comments on commit d6fb940

Please sign in to comment.