Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
29 changes: 21 additions & 8 deletions deadlock.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,14 @@ func (m *Mutex) Lock() {
currID++
}
counterMu.Unlock()
lock(m.mu.Lock, m, false)

// shortcut for disabled deadlock detection to prevent extra copying of `m.mu.Lock` to the heap
if Opts.Disable {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what if this check was moved above the counterMu lock?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

m.mu.Lock()
return
}

lockEnabled(m.mu.Lock, m, false)
}

// Unlock unlocks the mutex.
Expand Down Expand Up @@ -121,7 +128,12 @@ func (m *RWMutex) Lock() {
}
counterMu.Unlock()

lock(m.mu.Lock, m, false)
if Opts.Disable {
m.mu.Lock()
return
}

lockEnabled(m.mu.Lock, m, false)
}

// Unlock unlocks the mutex for writing. It is a run-time error if rw is
Expand Down Expand Up @@ -149,7 +161,12 @@ func (m *RWMutex) RLock() {
}
counterMu.Unlock()

lock(m.mu.RLock, m, true)
if Opts.Disable {
m.mu.RLock()
return
}

lockEnabled(m.mu.RLock, m, true)
}

// RUnlock undoes a single RLock call;
Expand Down Expand Up @@ -189,11 +206,7 @@ func checkLockOrdering(skip int, p identifiable, gid int64) {
lo.checkLockOrdering(skip, p, gid)
}

func lock(lockFn func(), ptr identifiable, preLockCheckRecursiveLocking bool) {
if Opts.Disable {
lockFn()
return
}
func lockEnabled(lockFn func(), ptr identifiable, preLockCheckRecursiveLocking bool) {
// grab the current goroutine identifier
gid := goid.Get()
preLock(4, ptr, gid, preLockCheckRecursiveLocking)
Expand Down
21 changes: 21 additions & 0 deletions deadlock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,3 +275,24 @@ func TestRWMutexDoubleRLockFail(t *testing.T) {
t.Fatalf("expected 1 deadlocks, detected %d", deadlocks)
}
}

//go:noinline
func benchRWAlloc(mu *RWMutex, res *int) {
mu.Lock()
defer mu.Unlock() // defer prefers inlining for the benchmark
*res++
}

// BenchmarkRWMutexAlloc demonstrates there is one alloc per lock invocation.
func BenchmarkRWMutexAlloc(b *testing.B) {
disable := Opts.Disable
Opts.Disable = true
defer func() {
Opts.Disable = disable
}()
var mu *RWMutex = &RWMutex{}
var res int
for i := 0; i < b.N; i++ {
benchRWAlloc(mu, &res)
}
}