Senior
What synchronization primitives do you know?
sobes.tech AI
Answer from AI
In Go, there are several basic synchronization primitives for managing concurrent access to resources:
- Mutex (sync.Mutex) — provides mutual exclusion, blocking access to a critical section.
- RWMutex (sync.RWMutex) — an extended mutex that allows multiple readers to read simultaneously but blocks writers.
- WaitGroup (sync.WaitGroup) — allows waiting for a group of goroutines to finish.
- Cond (sync.Cond) — a condition variable for notifying goroutines about an event.
- Atomic operations (sync/atomic) — low-level operations for atomic read and write of variables.
Additionally, in Go, channels are widely used to synchronize goroutines and pass data between them without explicit use of mutexes.
Example of using Mutex:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
Example of using WaitGroup:
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
// work
}()
go func() {
defer wg.Done()
// work
}()
wg.Wait()