go:concurrency:cond
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?
- Implement producer-consumer patterns.
- Build your own blocking queues or resource pools.
- Coordinate state changes beyond simple locking.
When to use
- You need to wait for “state” changes, not just mutual exclusion.
- A channel-based solution is not convenient for your design.
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
- Always check the condition in a `for` loop (spurious wakeups can happen).
- `Wait()` must be called with the lock held.
- Prefer channels for many common cases; use `Cond` when you need advanced coordination.
Related
Hard words (English)
- condition variable /kənˈdɪʃən ˈveriəbəl/: biến điều kiện
- signal /ˈsɪɡnəl/: đánh thức/báo hiệu
- broadcast /ˈbrɔːdkæst/: đánh thức tất cả (Cond.Broadcast)
- producer-consumer /prəˈduːsər kənˈsuːmər/: mô hình sản xuất-tiêu thụ
- spurious wakeup /ˈspjʊriəs ˈweɪkʌp/: thức dậy “ảo” (không có tín hiệu thật)
- coordinate /koʊˈɔːrdɪneɪt/: điều phối
go/concurrency/cond.txt · Last modified: by phong2018
