1 // Copyright 2011 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.
12 // Cond implements a condition variable, a rendezvous point
13 // for goroutines waiting for or announcing the occurrence
16 // Each Cond has an associated Locker L (often a *Mutex or *RWMutex),
17 // which must be held when changing the condition and
18 // when calling the Wait method.
20 // A Cond can be created as part of other structures.
21 // A Cond must not be copied after first use.
23 // L is held while observing or changing the condition
27 waiters
uint32 // number of waiters
31 // NewCond returns a new Cond with Locker l.
32 func NewCond(l Locker
) *Cond
{
36 // Wait atomically unlocks c.L and suspends execution
37 // of the calling goroutine. After later resuming execution,
38 // Wait locks c.L before returning. Unlike in other systems,
39 // Wait cannot return unless awoken by Broadcast or Signal.
41 // Because c.L is not locked when Wait first resumes, the caller
42 // typically cannot assume that the condition is true when
43 // Wait returns. Instead, the caller should Wait in a loop:
49 // ... make use of condition ...
52 func (c
*Cond
) Wait() {
57 atomic
.AddUint32(&c
.waiters
, 1)
62 runtime_Syncsemacquire(&c
.sema
)
66 // Signal wakes one goroutine waiting on c, if there is any.
68 // It is allowed but not required for the caller to hold c.L
70 func (c
*Cond
) Signal() {
74 // Broadcast wakes all goroutines waiting on c.
76 // It is allowed but not required for the caller to hold c.L
78 func (c
*Cond
) Broadcast() {
82 func (c
*Cond
) signalImpl(all
bool) {
88 old
:= atomic
.LoadUint32(&c
.waiters
)
99 if atomic
.CompareAndSwapUint32(&c
.waiters
, old
, new) {
103 runtime_Syncsemrelease(&c
.sema
, old
-new)
109 // copyChecker holds back pointer to itself to detect object copying.
110 type copyChecker
uintptr
112 func (c
*copyChecker
) check() {
113 if uintptr(*c
) != uintptr(unsafe
.Pointer(c
)) &&
114 !atomic
.CompareAndSwapUintptr((*uintptr)(c
), 0, uintptr(unsafe
.Pointer(c
))) &&
115 uintptr(*c
) != uintptr(unsafe
.Pointer(c
)) {
116 panic("sync.Cond is copied")