• English
  • Go's sync Package

    The Go sync package provides low-level concurrency primitives for memory synchronization and thread-safe state management across goroutines, complementing Go’s channel-based communication model.

    Key Primitives:

    • sync.WaitGroup: Blocks execution until a set of concurrent goroutines finishes (Add, Done, Wait).
    • sync.Mutex / sync.RWMutex: Provides mutual exclusion locks to protect critical sections from race conditions. RWMutex allows concurrent readers but a single writer.
    • sync.Once: Guarantees that a given function executes exactly once across multiple goroutines (ideal for thread-safe lazy initialization).
    • sync.Pool: Thread-safe temporary object pool designed to reuse memory allocations and minimize garbage collection (GC) pressure.
    • sync.Map: A concurrent map optimized for specific access patterns, such as read-heavy workloads or disjoint key sets.
    • sync.Cond: A condition variable allowing goroutines to wait for or notify others about specific state changes.

    While idiomatic Go favors "sharing memory by communicating" via channels, the sync package is essential for fine-grained locking, high-performance shared-state access, and memory optimization.