Skip to content

Commit

Permalink
concurrency/mutexmap Move Unlock to after operation (#101)
Browse files Browse the repository at this point in the history
Signed-off-by: joshvanl <[email protected]>
  • Loading branch information
JoshVanL authored Sep 9, 2024
1 parent 26b564d commit 502671b
Showing 1 changed file with 27 additions and 20 deletions.
47 changes: 27 additions & 20 deletions concurrency/mutexmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,50 +58,57 @@ func (a *mutexMap[T]) Lock(key T) {
a.lock.RLock()
mutex, ok := a.items[key]
a.lock.RUnlock()
if ok {
mutex.Lock()
return
}

a.lock.Lock()
mutex, ok = a.items[key]
if !ok {
a.lock.Lock()
mutex, ok = a.items[key]
if !ok {
mutex = &sync.RWMutex{}
a.items[key] = mutex
}
a.lock.Unlock()
mutex = &sync.RWMutex{}
a.items[key] = mutex
}
a.lock.Unlock()
mutex.Lock()
}

func (a *mutexMap[T]) Unlock(key T) {
a.lock.RLock()
mutex, ok := a.items[key]
a.lock.RUnlock()
if ok {
mutex.Unlock()
}
a.lock.RUnlock()
}

func (a *mutexMap[T]) RLock(key T) {
a.lock.RLock()
mutex, ok := a.items[key]
a.lock.RUnlock()

if ok {
mutex.RLock()
return
}

a.lock.Lock()
mutex, ok = a.items[key]
if !ok {
a.lock.Lock()
mutex, ok = a.items[key]
if !ok {
mutex = &sync.RWMutex{}
a.items[key] = mutex
}
a.lock.Unlock()
mutex = &sync.RWMutex{}
a.items[key] = mutex
}
a.lock.Unlock()
mutex.RLock()
}

func (a *mutexMap[T]) RUnlock(key T) {
a.lock.RLock()
mutex, ok := a.items[key]
a.lock.RUnlock()
if ok {
mutex.RUnlock()
}
a.lock.RUnlock()
}

func (a *mutexMap[T]) Delete(key T) {
Expand All @@ -113,21 +120,21 @@ func (a *mutexMap[T]) Delete(key T) {
func (a *mutexMap[T]) DeleteUnlock(key T) {
a.lock.Lock()
mutex, ok := a.items[key]
delete(a.items, key)
a.lock.Unlock()
if ok {
mutex.Unlock()
}
delete(a.items, key)
a.lock.Unlock()
}

func (a *mutexMap[T]) DeleteRUnlock(key T) {
a.lock.Lock()
mutex, ok := a.items[key]
delete(a.items, key)
a.lock.Unlock()
if ok {
mutex.RUnlock()
}
delete(a.items, key)
a.lock.Unlock()
}

func (a *mutexMap[T]) Clear() {
Expand Down

0 comments on commit 502671b

Please sign in to comment.