From 172c1d2e20431aaee1bee6e300d1abaef657d8fc Mon Sep 17 00:00:00 2001 From: soypat Date: Wed, 1 Nov 2023 21:16:26 -0300 Subject: [PATCH] implement trylock --- src/sync/mutex.go | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/sync/mutex.go b/src/sync/mutex.go index e12bf40c17..40cca2bbf3 100644 --- a/src/sync/mutex.go +++ b/src/sync/mutex.go @@ -32,9 +32,21 @@ func (m *Mutex) Unlock() { // Wake up a blocked task, if applicable. if t := m.blocked.Pop(); t != nil { scheduleTask(t) - } else { - m.locked = false } + m.locked = false +} + +// TryLock tries to lock m and reports whether it succeeded. +// +// Note that while correct uses of TryLock do exist, they are rare, +// and use of TryLock is often a sign of a deeper problem +// in a particular use of mutexes. +func (m *Mutex) TryLock() bool { + if m.locked { + return false + } + m.Lock() + return true } type RWMutex struct {