1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package sync provides basic synchronization primitives such as mutual
6 // exclusion locks. Other than the Once and WaitGroup types, most are intended
7 // for use by low-level library routines. Higher-level synchronization is
8 // better done via channels and communication.
10 // Values containing the types defined in this package should not be copied.
19 // A Mutex is a mutual exclusion lock.
20 // Mutexes can be created as part of other structures;
21 // the zero value for a Mutex is an unlocked mutex.
23 // A Mutex must not be copied after first use.
29 // A Locker represents an object that can be locked and unlocked.
30 type Locker
interface {
36 mutexLocked
= 1 << iota // mutex is locked
38 mutexWaiterShift
= iota
42 // If the lock is already in use, the calling goroutine
43 // blocks until the mutex is available.
44 func (m
*Mutex
) Lock() {
45 // Fast path: grab unlocked mutex.
46 if atomic
.CompareAndSwapInt32(&m
.state
, 0, mutexLocked
) {
48 race
.Acquire(unsafe
.Pointer(m
))
57 new := old | mutexLocked
58 if old
&mutexLocked
!= 0 {
59 if runtime_canSpin(iter
) {
60 // Active spinning makes sense.
61 // Try to set mutexWoken flag to inform Unlock
62 // to not wake other blocked goroutines.
63 if !awoke
&& old
&mutexWoken
== 0 && old
>>mutexWaiterShift
!= 0 &&
64 atomic
.CompareAndSwapInt32(&m
.state
, old
, old|mutexWoken
) {
71 new = old
+ 1<<mutexWaiterShift
74 // The goroutine has been woken from sleep,
75 // so we need to reset the flag in either case.
76 if new&mutexWoken
== 0 {
77 panic("sync: inconsistent mutex state")
81 if atomic
.CompareAndSwapInt32(&m
.state
, old
, new) {
82 if old
&mutexLocked
== 0 {
85 runtime_Semacquire(&m
.sema
)
92 race
.Acquire(unsafe
.Pointer(m
))
97 // It is a run-time error if m is not locked on entry to Unlock.
99 // A locked Mutex is not associated with a particular goroutine.
100 // It is allowed for one goroutine to lock a Mutex and then
101 // arrange for another goroutine to unlock it.
102 func (m
*Mutex
) Unlock() {
105 race
.Release(unsafe
.Pointer(m
))
108 // Fast path: drop lock bit.
109 new := atomic
.AddInt32(&m
.state
, -mutexLocked
)
110 if (new+mutexLocked
)&mutexLocked
== 0 {
111 panic("sync: unlock of unlocked mutex")
116 // If there are no waiters or a goroutine has already
117 // been woken or grabbed the lock, no need to wake anyone.
118 if old
>>mutexWaiterShift
== 0 || old
&(mutexLocked|mutexWoken
) != 0 {
121 // Grab the right to wake someone.
122 new = (old
- 1<<mutexWaiterShift
) | mutexWoken
123 if atomic
.CompareAndSwapInt32(&m
.state
, old
, new) {
124 runtime_Semrelease(&m
.sema
)