Sobes.tech
Senior

What synchronization primitives are available in Go?

sobes.tech AI

Answer from AI

In Go, there are several synchronization primitives that help manage concurrent access to resources:

  • Mutex (sync.Mutex) — provides mutual exclusion by locking access to a critical section.

  • RWMutex (sync.RWMutex) — an extension of Mutex that allows multiple readers to access simultaneously but blocks writers when there are active readers.

  • WaitGroup (sync.WaitGroup) — used to wait for a group of goroutines to finish.

  • Cond (sync.Cond) — a condition variable for notifying goroutines about a certain state.

  • Once (sync.Once) — ensures a function is only executed once.

  • Atomic operations (sync/atomic) — low-level operations for atomic read/write of values without locks.

Example of using Mutex:

var mu sync.Mutex
var counter int

func increment() {
    mu.Lock()
    defer mu.Unlock()
    counter++
}

These primitives allow for efficient and safe handling of concurrency in Go.