Skip to content

Commit 172c1d2

Browse files
committed
implement trylock
1 parent 938ce22 commit 172c1d2

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

src/sync/mutex.go

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,21 @@ func (m *Mutex) Unlock() {
3232
// Wake up a blocked task, if applicable.
3333
if t := m.blocked.Pop(); t != nil {
3434
scheduleTask(t)
35-
} else {
36-
m.locked = false
3735
}
36+
m.locked = false
37+
}
38+
39+
// TryLock tries to lock m and reports whether it succeeded.
40+
//
41+
// Note that while correct uses of TryLock do exist, they are rare,
42+
// and use of TryLock is often a sign of a deeper problem
43+
// in a particular use of mutexes.
44+
func (m *Mutex) TryLock() bool {
45+
if m.locked {
46+
return false
47+
}
48+
m.Lock()
49+
return true
3850
}
3951

4052
type RWMutex struct {

0 commit comments

Comments
 (0)