summaryrefslogtreecommitdiffhomepage
path: root/pkg/sync/tmutex_unsafe.go
diff options
context:
space:
mode:
authorKevin Krakauer <krakauer@google.com>2020-01-24 10:42:43 -0800
committerKevin Krakauer <krakauer@google.com>2020-01-24 10:42:43 -0800
commit7636478a316692328097c9e70d38ff878539afb3 (patch)
tree637787744e7f6a10bb4a5acb926447d451cb500f /pkg/sync/tmutex_unsafe.go
parentb7853f688b4bcd3465c0c3087fcbd8d53bdf26ae (diff)
parent3db317390b5cc491d680fc4a5fc7b8372890b4da (diff)
Merge branch 'master' into ipt-udp-matchers
Diffstat (limited to 'pkg/sync/tmutex_unsafe.go')
-rw-r--r--pkg/sync/tmutex_unsafe.go49
1 files changed, 49 insertions, 0 deletions
diff --git a/pkg/sync/tmutex_unsafe.go b/pkg/sync/tmutex_unsafe.go
new file mode 100644
index 000000000..3dd15578b
--- /dev/null
+++ b/pkg/sync/tmutex_unsafe.go
@@ -0,0 +1,49 @@
+// Copyright 2019 The gVisor Authors.
+//
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build go1.13
+// +build !go1.15
+
+// When updating the build constraint (above), check that syncMutex matches the
+// standard library sync.Mutex definition.
+
+package sync
+
+import (
+ "sync"
+ "sync/atomic"
+ "unsafe"
+)
+
+// Mutex is a try lock.
+type Mutex struct {
+ sync.Mutex
+}
+
+type syncMutex struct {
+ state int32
+ sema uint32
+}
+
+func (m *Mutex) state() *int32 {
+ return &(*syncMutex)(unsafe.Pointer(&m.Mutex)).state
+}
+
+const (
+ mutexUnlocked = 0
+ mutexLocked = 1
+)
+
+// TryLock tries to aquire the mutex. It returns true if it succeeds and false
+// otherwise. TryLock does not block.
+func (m *Mutex) TryLock() bool {
+ if atomic.CompareAndSwapInt32(m.state(), mutexUnlocked, mutexLocked) {
+ if RaceEnabled {
+ RaceAcquire(unsafe.Pointer(&m.Mutex))
+ }
+ return true
+ }
+ return false
+}