Skip to content

Commit

Permalink
chore(pkg/database): use atomic for waitingCount in instrumentedRWMutex
Browse files Browse the repository at this point in the history
Signed-off-by: Artur Melanchyk <[email protected]>
  • Loading branch information
arturmelanchyk committed Jan 31, 2024
1 parent 982b80a commit 98de1f1
Showing 1 changed file with 7 additions and 16 deletions.
23 changes: 7 additions & 16 deletions pkg/database/instrumented_rwmutex.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,34 +18,30 @@ package database

import (
"sync"
"sync/atomic"
"time"
)

type instrumentedRWMutex struct {
rwmutex sync.RWMutex

trwmutex sync.RWMutex
waitingCount int
waitingCount int64
lastReleaseAt time.Time
}

func (imux *instrumentedRWMutex) State() (waitingCount int, lastReleaseAt time.Time) {
imux.trwmutex.RLock()
defer imux.trwmutex.RUnlock()

return imux.waitingCount, imux.lastReleaseAt
return int(atomic.LoadInt64(&imux.waitingCount)), imux.lastReleaseAt
}

func (imux *instrumentedRWMutex) Lock() {
imux.trwmutex.Lock()
imux.waitingCount++
imux.trwmutex.Unlock()
atomic.AddInt64(&imux.waitingCount, 1)
defer atomic.AddInt64(&imux.waitingCount, -1)

imux.rwmutex.Lock()

imux.trwmutex.Lock()
imux.waitingCount--
imux.trwmutex.Unlock()
}

func (imux *instrumentedRWMutex) Unlock() {
Expand All @@ -58,15 +54,10 @@ func (imux *instrumentedRWMutex) Unlock() {
}

func (imux *instrumentedRWMutex) RLock() {
imux.trwmutex.Lock()
imux.waitingCount++
imux.trwmutex.Unlock()
atomic.AddInt64(&imux.waitingCount, 1)
defer atomic.AddInt64(&imux.waitingCount, -1)

imux.rwmutex.RLock()

imux.trwmutex.Lock()
imux.waitingCount--
imux.trwmutex.Unlock()
}

func (imux *instrumentedRWMutex) RUnlock() {
Expand Down

0 comments on commit 98de1f1

Please sign in to comment.