Sobes.tech
Middle

What are the synchronization primitives in Go?

sobes.tech AI

Answer from AI

  • sync.Mutex: Mutual exclusion for restricting access to a resource to only one goroutine at a time.
  • sync.RWMutex: Mutual exclusion with support for reading and writing. Allows multiple goroutines to read the resource simultaneously, but only one to write.
  • sync.WaitGroup: Waiting for a set of goroutines to finish. Used for coordinating the execution of multiple background tasks.
  • sync.Once: Ensures that a certain action is performed only once, even when called from multiple goroutines.
  • sync.Cond: Conditional variable that allows goroutines to wait for a certain condition before continuing execution. Works in conjunction with a mutex.
  • Channels (chan): Data type for safe data exchange between goroutines and synchronizing their work.
    • Unbuffered channels: Synchronous send and receive. The sender blocks until the receiver accepts the value, and vice versa.
    • Buffered channels: Asynchronous send until the buffer is full. The sender blocks only when the buffer is full. The receiver blocks when the buffer is empty.