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 {