Sobes.tech
Senior

What specific synchronization primitives are available in Go?

sobes.tech AI

Answer from AI

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

  • Mutex (sync.Mutex) — a basic mutex for mutual exclusion. It allows locking a section of code so that only one goroutine can execute it.

  • RWMutex (sync.RWMutex) — an extended mutex supporting multiple readers or one writer. It improves performance during frequent reads and infrequent writes.

  • WaitGroup (sync.WaitGroup) — allows waiting for a group of goroutines to finish. It is used for synchronization of completion.

  • Cond (sync.Cond) — a condition variable for implementing waiting and notification between goroutines.

  • Atomic operations (sync/atomic) — low-level atomic operations for safely modifying variables without locks.

Example of using Mutex:

var mu sync.Mutex
var counter int

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