Skip to content

Commit

Permalink
sync: in TryLock try to acquire mutex even if state is not 0
Browse files Browse the repository at this point in the history
For #45435

Change-Id: I728accd9a53c1826243f52aa04dc2a0a1dfdaadf
Reviewed-on: https://go-review.googlesource.com/c/go/+/363672
Trust: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Dmitry Vyukov <dvyukov@google.com>
  • Loading branch information
ianlancetaylor committed Nov 16, 2021
1 parent 8656895 commit fdd6793
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions src/sync/mutex.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,22 @@ func (m *Mutex) Lock() {
// and use of TryLock is often a sign of a deeper problem
// in a particular use of mutexes.
func (m *Mutex) TryLock() bool {
if atomic.CompareAndSwapInt32(&m.state, 0, mutexLocked) {
if race.Enabled {
race.Acquire(unsafe.Pointer(m))
}
return true
old := m.state
if old&(mutexLocked|mutexStarving) != 0 {
return false
}

// There may be a goroutine waiting for the mutex, but we are
// running now and can try to grab the mutex before that
// goroutine wakes up.
if !atomic.CompareAndSwapInt32(&m.state, old, old|mutexLocked) {
return false
}

if race.Enabled {
race.Acquire(unsafe.Pointer(m))
}
return false
return true
}

func (m *Mutex) lockSlow() {
Expand Down

0 comments on commit fdd6793

Please sign in to comment.