Table of Contents

sync.Cond

What is it?

`sync.Cond` is a condition variable. It lets goroutines wait until a certain condition becomes true, and be signaled when it changes.

What is it used for?

When to use

Example (producer/consumer)

package main
 
import "sync"
 
type Queue struct {
    mu   sync.Mutex
    cond *sync.Cond
    data []int
}
 
func NewQueue() *Queue {
    q := &Queue{}
    q.cond = sync.NewCond(&q.mu)
    return q
}
 
func (q *Queue) Push(v int) {
    q.mu.Lock()
    q.data = append(q.data, v)
    q.mu.Unlock()
    q.cond.Signal() // wake one waiter
}
 
func (q *Queue) Pop() int {
    q.mu.Lock()
    defer q.mu.Unlock()
 
    for len(q.data) == 0 {
        q.cond.Wait() // unlocks mu, waits, then re-locks mu
    }
 
    v := q.data[0]
    q.data = q.data[1:]
    return v
}

Notes / pitfalls

Hard words (English)