summaryrefslogtreecommitdiffhomepage
path: root/pkg/sync/tmutex_unsafe.go
blob: 3c32f8371b2a0e0d035be0d268b2291fbee9e77a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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"
)

// TMutex is a try lock.
type TMutex struct {
	sync.Mutex
}

type syncMutex struct {
	state int32
	sema  uint32
}

func (m *TMutex) 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 *TMutex) TryLock() bool {
	if atomic.CompareAndSwapInt32(m.state(), mutexUnlocked, mutexLocked) {
		if RaceEnabled {
			RaceAcquire(unsafe.Pointer(&m.Mutex))
		}
		return true
	}
	return false
}