aboutsummaryrefslogtreecommitdiff
path: root/libgo/go/sync/mutex.go
diff options
context:
space:
mode:
Diffstat (limited to 'libgo/go/sync/mutex.go')
-rw-r--r--libgo/go/sync/mutex.go24
1 files changed, 24 insertions, 0 deletions
diff --git a/libgo/go/sync/mutex.go b/libgo/go/sync/mutex.go
index 3028552..18b2ced 100644
--- a/libgo/go/sync/mutex.go
+++ b/libgo/go/sync/mutex.go
@@ -81,6 +81,30 @@ func (m *Mutex) Lock() {
m.lockSlow()
}
+// 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 {
+ 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 true
+}
+
func (m *Mutex) lockSlow() {
var waitStartTime int64
starving := false