The previous article covered the most commonly used sync primitives: WaitGroup for goroutine coordination and Mutex/RWMutex for protecting shared state. The sync package has three more specialized tools, Cond, Once and Pool, for narrower problems that still come up often in concurrent programs. Each one covers a case where the general-purpose primitives don't fit or would need awkward workarounds.
sync.Cond
A sync.Mutex protects a critical section. Sometimes a goroutine also has to wait for a condition to become true, such as a queue having items or a flag being set.
The naive approach is to poll in a loop:
for len(queue) == 0 { // spin, burning CPU while waiting}This wastes a CPU core. A slightly better version uses time.Sleep inside the loop, but it still polls at a fixed interval and introduces artificial latency.
With sync.Cond, a goroutine can sleep until another goroutine that knows the condition has changed wakes it explicitly.
Structure
You create a Cond with sync.NewCond, which takes a sync.Locker, typically a *sync.Mutex or *sync.RWMutex:
var mu sync.Mutexcond := sync.NewCond(&mu)The three methods on Cond are:
| Method | Description |
|---|---|
Wait() | Atomically unlocks the mutex and suspends the goroutine. Reacquires the lock before returning when woken. |
Signal() | Wakes one goroutine waiting on this Cond. |
Broadcast() | Wakes all goroutines waiting on this Cond. |
Always call Wait inside a for loop, never inside an if statement:
mu.Lock()for !conditionMet() { cond.Wait()}// condition is now true — safe to proceedmu.Unlock()The loop is necessary because of spurious wakeups: Wait may return without Signal or Broadcast having been called. The loop re-checks the condition and sleeps again if it is still false. This pattern is standard for condition variables across all languages.
Example: producer and consumer
package mainimport ( "fmt" "sync" "time")func main() { var mu sync.Mutex cond := sync.NewCond(&mu) queue := make([]int, 0) // consumer: sleeps until items are available go func() { mu.Lock() for len(queue) == 0 { cond.Wait() } item := queue[0] queue = queue[1:] mu.Unlock() fmt.Printf("consumed: %d\n", item) }() // producer: adds an item and signals the consumer time.Sleep(50 * time.Millisecond) mu.Lock() queue = append(queue, 42) cond.Signal() mu.Unlock() time.Sleep(100 * time.Millisecond)}The consumer calls Wait, which atomically releases the lock and suspends. The producer acquires the lock, appends to the queue, calls Signal to wake one waiting goroutine, and releases the lock. The consumer wakes up, reacquires the lock, finds the queue non-empty, and processes the item.
Use Signal when only one waiting goroutine needs to be woken and can handle the changed condition alone. Use Broadcast when all waiters need to re-evaluate, for example when a shared resource becomes available and multiple goroutines are competing for it.
sync.Once
sync.Once ensures that a function runs exactly once, regardless of how many goroutines call it concurrently. After the first call completes, all subsequent calls are no-ops.
The entire API is a single method:
var once sync.Onceonce.Do(func() { // runs exactly once, ever})Do is thread-safe. If multiple goroutines call Do at the same time, exactly one executes the function; the others block until it returns. Once the function has returned, all future calls to Do return immediately without re-executing.
Uses
The main use is lazy initialization. Initializing a resource at package load time costs you even if the resource is never needed, so you initialize it on first use instead:
package mainimport ( "database/sql" "fmt" "sync" _ "github.com/lib/pq")var ( db *sql.DB once sync.Once)func getDB() *sql.DB { once.Do(func() { var err error dsn := "postgres://localhost/mydb?sslmode=disable" db, err = sql.Open("postgres", dsn) if err != nil { panic(err) } }) return db}func main() { conn := getDB() // first call: opens the connection pool fmt.Println(conn != nil) conn2 := getDB() // subsequent calls: returns the same instance fmt.Println(conn == conn2) // true}getDB creates the connection pool on its first call, and only once, no matter how many concurrent callers arrive at the same moment. Every subsequent call returns the same *sql.DB instance.
Package-level initialization is another common use, particularly for test helpers or optional features that are expensive to set up. Like init(), the function runs only once, and like on-demand initialization, it runs only when first needed.
sync.Pool
A sync.Pool is a thread-safe free list: a pool of objects you save and reuse instead of allocating and garbage-collecting them on every use.
Programs with high request throughput, like HTTP servers, parsers and encoders, allocate and free many short-lived objects in rapid succession, and each allocation adds pressure on the garbage collector. A Pool lets you recycle those objects instead of creating new ones all the time, which cuts GC overhead and raises sustained throughput.
Structure
var pool = sync.Pool{ New: func() any { return new(bytes.Buffer) },}The New field is a factory function called when Get needs an object and the pool is empty. If New is nil and the pool is empty, Get returns nil.
The two methods are:
| Method | Description |
|---|---|
Get() | Retrieves an object from the pool. Calls New if the pool is empty. Returns any. |
Put(x any) | Returns an object to the pool for future reuse. |
Example: buffer pool for encoding
A common pattern is pooling bytes.Buffer objects for JSON encoding in a hot path:
package mainimport ( "bytes" "encoding/json" "fmt" "sync")var bufPool = sync.Pool{ New: func() any { return new(bytes.Buffer) },}type Response struct { Message string `json:"message"`}func encode(v any) ([]byte, error) { buf := bufPool.Get().(*bytes.Buffer) buf.Reset() defer bufPool.Put(buf) if err := json.NewEncoder(buf).Encode(v); err != nil { return nil, err } return buf.Bytes(), nil}func main() { data, err := encode(Response{Message: "hello"}) if err != nil { panic(err) } fmt.Println(string(data))}Get retrieves a buffer from the pool (or allocates one if the pool is empty). After resetting it with buf.Reset(), the buffer is used for encoding. defer bufPool.Put(buf) returns the buffer to the pool when the function exits, making it available for the next call.
Under sustained load, the pool reaches a steady state where buffers cycle between in use and available, and few new allocations are needed. The standard library's fmt and encoding/json packages use sync.Pool internally for this reason.
How the pool works
Internally, Pool maintains a per-P (per-processor) local list. Put stores the object in the current goroutine's P's local slot. Get checks the local slot first, then steals from other Ps, then calls New.
The Go garbage collector may clear the pool at any collection cycle, because objects in the pool are not shielded from GC. That's by design: Pool is a performance optimization and keeps nothing for you, so your program has to cope with an empty pool at any point.
What this means in practice
sync.Cond, sync.Once, and sync.Pool each solve a specific problem that WaitGroup and the mutex family leave uncovered.
Use Cond when a goroutine needs to sleep until another goroutine signals a condition, especially when that condition is more involved than receiving a value from a channel.
Use Once for lazy, thread-safe initialization of resources that are expensive to create or that must exist as exactly one instance.
Use Pool to reduce per-operation allocation overhead in throughput-sensitive paths, knowing the GC may clear the pool at any time.
Between this article and the previous one, that makes six primitives: WaitGroup, Mutex, RWMutex, Cond, Once and Pool. They cover the most common coordination and memory-management problems in concurrent Go.