Skip to content

Commit fdd6793

Browse files
sync: in TryLock try to acquire mutex even if state is not 0
For #45435 Change-Id: I728accd9a53c1826243f52aa04dc2a0a1dfdaadf Reviewed-on: https://go-review.googlesource.com/c/go/+/363672 Trust: Ian Lance Taylor <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> Reviewed-by: Dmitry Vyukov <[email protected]>
1 parent 8656895 commit fdd6793

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

src/sync/mutex.go

+15-6
Original file line numberDiff line numberDiff line change
@@ -87,13 +87,22 @@ func (m *Mutex) Lock() {
8787
// and use of TryLock is often a sign of a deeper problem
8888
// in a particular use of mutexes.
8989
func (m *Mutex) TryLock() bool {
90-
if atomic.CompareAndSwapInt32(&m.state, 0, mutexLocked) {
91-
if race.Enabled {
92-
race.Acquire(unsafe.Pointer(m))
93-
}
94-
return true
90+
old := m.state
91+
if old&(mutexLocked|mutexStarving) != 0 {
92+
return false
93+
}
94+
95+
// There may be a goroutine waiting for the mutex, but we are
96+
// running now and can try to grab the mutex before that
97+
// goroutine wakes up.
98+
if !atomic.CompareAndSwapInt32(&m.state, old, old|mutexLocked) {
99+
return false
100+
}
101+
102+
if race.Enabled {
103+
race.Acquire(unsafe.Pointer(m))
95104
}
96-
return false
105+
return true
97106
}
98107

99108
func (m *Mutex) lockSlow() {

0 commit comments

Comments
 (0)