sync#

Go’s sync package is based on synchronizing by sharing memory, providing low-level primitives for memory-access synchronization and critical section protection among goroutines. Unlike channels, which share memory by communicating, sync deals with traditional locking and signaling primitives.


1. sync.WaitGroup#

Used to establish a Join Point waiting for the completion of concurrent branches in Go’s Fork-Join model.

For single goroutine cancellation or waiting, context cancellation is preferred, but WaitGroup is the standard tool for waiting on multiple concurrent tasks.

  • .Add(delta int): Adds delta to the internal counter.
  • .Done(): Decrements the counter by 1. Always invoke via defer to ensure execution even during panics.
  • .Wait(): Blocks the calling goroutine until the counter drops to zero.

Fork-Join Example#

func main() {
    var wg sync.WaitGroup
    urls := []string{"https://golang.org", "https://google.com", "https://github.com"}

    for _, url := range urls {
        // 1. wg.Add must be called in the parent goroutine before launching
        wg.Add(1)
        go func(u string) {
            defer wg.Done()
            fetch(u)
        }(url) // 2. Pass loop variables explicitly as parameters
    }

    // Join Point: Block until all goroutines finish
    wg.Wait()
    fmt.Println("All fetches completed!")
}

Critical Antipatterns to Avoid#

  1. Calling wg.Add(1) inside the goroutine:
    • If the main goroutine reaches wg.Wait() before the spawned goroutines begin executing, the counter remains 0 and Wait() returns immediately, causing the program to terminate prematurely.
  2. Passing sync.WaitGroup by value:
    • WaitGroup contains internal counter state. Passing by value creates a copy, leaving the original counter untouched and causing wg.Wait() to deadlock. Always pass a pointer (*sync.WaitGroup).

2. sync.Mutex & sync.RWMutex#

Mutual exclusion locks designed to control concurrent access to shared resources and prevent data races.

sync.Mutex (Mutual Exclusion)#

  • .Lock(): Acquires the lock. If another goroutine holds the lock, the caller blocks until it is available.
  • .Unlock(): Releases the lock. Always pair with defer mu.Unlock() to ensure locks are freed even during panics.

sync.RWMutex (Reader/Writer Lock)#

Reduces the cross-section of critical sections by separating read and write access.

  • .RLock() / .RUnlock(): Read-only lock. An arbitrary number of readers can hold read locks concurrently as long as no writer holds the lock.
  • .Lock() / .Unlock(): Exclusive write lock. Only a single writer can hold this lock.

Warning: RWMutex Self-Deadlock & Double-Checked Locking#

Go’s sync.RWMutex does not support lock promotion (upgrading an active read lock to a write lock). Requesting a write lock while still holding a read lock results in an immediate self-deadlock.

// Idiomatic cache pattern with Double-Checked Locking
func (c *Cache) GetOrSet(key, defaultValue string) string {
    // 1. Fast path: check with read lock
    c.mu.RLock()
    val, exists := c.data[key]
    c.mu.RUnlock() // Release immediately (do not defer)
    if exists {
        return val
    }

    // 2. Slow path: acquire write lock
    c.mu.Lock()
    defer c.mu.Unlock()

    // 3. Double-Check: another goroutine might have populated it between RUnlock and Lock
    if val, exists := c.data[key]; exists {
        return val
    }
    c.data[key] = defaultValue
    return defaultValue
}

3. sync.Cond (Condition Variables)#

A rendezvous point for goroutines waiting for or announcing the occurrence of an event.

Why use sync.Cond?#

  • Busy Waiting: Infinite loops consume 100% of a CPU core.
  • Sleep Polling: time.Sleep introduces artificial latency and wastes cycles.
  • sync.Cond: Suspends the goroutine in the runtime wait queue (0% CPU utilization) and wakes it up instantaneously when an event is signaled.

Core Methods#

  • c.Wait(): [Hidden Side-Effect] Automatically calls c.L.Unlock() to release the lock and suspends the goroutine. Upon waking up from a signal, it re-acquires c.L.Lock() before returning.
  • c.Signal(): Wakes up the single longest-waiting goroutine (1:1).
  • c.Broadcast(): Wakes up all waiting goroutines simultaneously (1:N).

Golden Rule: Always Loop with for, Never if#

Upon waking up, another goroutine may have already acquired the lock and consumed the resource, or a spurious wakeup may have occurred. Always wrap c.Wait() inside a for !condition loop:

c.L.Lock()
for !condition {
    c.Wait()
}
// Condition safely validated while holding the lock
c.L.Unlock()

Standard Pattern (Producer-Consumer)#

var (
    mu    sync.Mutex
    cond  = sync.NewCond(&mu)
    queue []string
)

// Consumer
go func() {
    cond.L.Lock()
    for len(queue) == 0 {
        cond.Wait() // Suspended with 0% CPU until data arrives
    }
    item := queue[0]
    queue = queue[1:]
    fmt.Println("Processed:", item)
    cond.L.Unlock()
}()

// Producer
cond.L.Lock()
queue = append(queue, "task-1")
cond.Signal() // Awaken 1 waiting worker (use cond.Broadcast() for all)
cond.L.Unlock()

Lock Acquisition Order and Condition Re-checking#

In concurrent execution, it is indeterminate whether the Consumer or Producer acquires the lock first. The for len(queue) == 0 loop ensures correctness regardless of arrival order:

  • If Consumer arrives first: The queue is empty, so it enters cond.Wait(), releasing the lock and sleeping. When the Producer acquires the lock, appends data, calls Signal(), and unlocks, the Consumer re-acquires the lock, wakes up, and consumes the item.
  • If Producer arrives first: It appends data and calls cond.Signal() (ignored since no goroutine is waiting yet). When the Consumer subsequently acquires the lock, len(queue) == 0 evaluates to false, so it bypasses cond.Wait() entirely and consumes the item immediately.

4. sync.Once#

Guarantees that a specific initialization function is executed exactly once throughout the program’s lifecycle, even across thousands of concurrent goroutines.

  • .Do(f func()): f must take no arguments and return no values.

Idiomatic Pattern: Safe Channel Closer#

Closing an already closed channel causes panic: close of closed channel. Using sync.Once ensures safe closing even with multiple concurrent exit paths:

type SafeChannel struct {
    done chan struct{}
    once sync.Once
}

func (sc *SafeChannel) Close() {
    sc.once.Do(func() {
        close(sc.done) // Safely closed exactly once
    })
}

Equivalent Pattern Without sync.Once (Mutex + select)#

In older or low-level codebases (such as Kubernetes’s StreamWatcher.Stop()), you will often see an equivalent pattern built with sync.Mutex and a non-blocking select.

  • How it works: For a pure signal channel (chan struct{}) that is never sent to and only closed, receiving (<-ch) becomes immediately ready the moment the channel is closed. Under a mutex lock, a select with a default branch checks whether the channel is already closed before calling close(). (Note: for channels that carry actual data, use an explicit closed bool flag under the mutex instead so you don’t accidentally consume a value.)
type SafeChannel struct {
    done chan struct{}
    mu   sync.Mutex
}

func (sc *SafeChannel) Close() {
    sc.mu.Lock()
    defer sc.mu.Unlock()

    // A closed channel is immediately readable; check before closing
    select {
    case <-sc.done:
        // Already closed; do nothing
    default:
        close(sc.done) // Close only if still open
    }
}

Caveats#

  • sync.Once tracks invocations on the Once instance itself, not the specific function passed to Do. Use distinct sync.Once variables for separate initialization tasks.

Go 1.21+ Generic Helpers: sync.OnceValue vs sync.OnceValues#

While sync.Once is a struct requiring explicit calls to .Do(func()), Go 1.21+ introduced higher-order functions that return callable (executable) functions directly.

1. sync.OnceValue[T] (Single Value)#

  • Signature: func OnceValue[T any](f func() T) func() T
  • Used for pure, infallible computations or settings where no error can occur.
var getHost = sync.OnceValue(func() string {
    return os.Getenv("HOST")
})

func main() {
    host := getHost() // Directly callable function
}

2. sync.OnceValues[T] (Value and Error)#

  • Signature: func OnceValues[T any](f func() (T, error)) func() (T, error)
  • Used for operations that may fail (DB connection, file I/O) following standard Go (T, error) conventions.
var getDB = sync.OnceValues(func() (*sql.DB, error) {
    return sql.Open("postgres", "connection_string")
})

func main() {
    db, err := getDB() // Directly callable returning (*sql.DB, error)
    if err != nil {
        log.Fatal(err)
    }
}

5. sync.Pool#

A concurrent object pool designed to reuse temporary objects and relieve Garbage Collector (GC) allocation pressure and stop-the-world pauses.

Core Architecture: Dynamic Pool, Not a Singleton#

  • sync.Pool is not a singleton holding only a single object.
  • It is a dynamic pool that scales up and down proportionally with the concurrent workload.
  • If 100 goroutines call Get() concurrently, the pool scales to 100 objects, and when returned with Put(), all 100 objects remain available for subsequent reuse.

Why is it in the sync Package? (Concurrency Optimization)#

Unlike a custom slice protected by a mutex, sync.Pool is deeply integrated with Go’s GMP scheduler:

  • Per-P Lock-Free Private Cache: Each logical processor (P) has its own lock-free private cache, eliminating lock contention even under massive concurrency.
  • Work-Stealing: If a processor’s local cache is empty, it steals idle objects from other processors.

Methods and the Truth About Reset()#

  • sync.Pool provides only two methods:
    • .Get() any: Retrieves an object or invokes New() if empty.
    • .Put(x any): Returns an object to the pool.
  • Reset() is NOT a sync.Pool method:
    • Reset() belongs to the underlying concrete object (such as bytes.Buffer).
    • Because sync.Pool stores any, it has no knowledge of the object’s internal structure and cannot clear it automatically.
    • Callers must explicitly invoke Reset() to prevent dirty reads or data contamination from prior operations.

Basic Usage#

var bufPool = sync.Pool{
    New: func() any {
        return new(bytes.Buffer) // Factory called when pool is empty
    },
}

func Render() string {
    // 1. Borrow and Type Assert
    buf := bufPool.Get().(*bytes.Buffer)
    defer func() {
        buf.Reset()      // Essential: object method to reset state
        bufPool.Put(buf) // 2. Return
    }()

    buf.WriteString("Hello, Pool!")
    return buf.String()
}

Practical Rules#

  1. Not a Permanent Cache: The Go runtime may sweep and reclaim objects in sync.Pool during any GC cycle. Never use it as a persistent store (e.g., Redis).
  2. Always Reset(): Reused objects retain stale data from prior operations. Always clean buffers before or after use.
  3. Use Homogeneous Objects: Store uniform items (e.g., standard byte buffers) rather than randomly-sized slices to maximize reuse efficiency.