Cond 通常应用于等待某个条件的一组 goroutine,等条件变为 true 的时候,其中一个 goroutine 或者所有的 goroutine 都会被唤醒执行。

sync.Cond 提供的方法

1
2
3
4
func NewCond(l Locker) *Cond {} // 创建一个 cond
func (c *Cond) Wait() {}        // 阻塞,等待唤醒
func (c *Cond) Signal() {}      // 唤醒一个等待者
func (c *Cond) Broadcast() {}   // 唤醒所有等待者

NewCond需要传入一个锁

1
2
3
func NewCond(l Locker) *Cond {
	return &Cond{L: l}
}

示例如下:

1
c := sync.NewCond(&sync.Mutex{})

调用Wait方法可以阻塞goroutine,但是在调用Wait方法时,需要先获取锁,

Wait方法实现如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/ Wait atomically unlocks c.L and suspends execution
// of the calling goroutine. After later resuming execution,
// Wait locks c.L before returning. Unlike in other systems,
// Wait cannot return unless awoken by Broadcast or Signal.
//
// Because c.L is not locked when Wait first resumes, the caller
// typically cannot assume that the condition is true when
// Wait returns. Instead, the caller should Wait in a loop:
//
//    c.L.Lock()
//    for !condition() {
//        c.Wait()
//    }
//    ... make use of condition ...
//    c.L.Unlock()
//
func (c *Cond) Wait() {
    c.checker.check()
    t := runtime_notifyListAdd(&c.notify)   // 加入到等待队列
    c.L.Unlock()                            // 解锁
    runtime_notifyListWait(&c.notify, t)    // 阻塞等待直到被唤醒
    c.L.Lock()                              // 加锁
}

参考