Middle+
What synchronization primitives did you use in Go?
sobes.tech AI
Answer from AI
In Go, the following primitives are used for goroutine synchronization:
- Mutex (sync.Mutex) — a basic mutex for mutual exclusion, blocks access to shared resources.
- RWMutex (sync.RWMutex) — a mutex with separate locks for reading and writing, allows multiple readers simultaneously but only one writer.
- WaitGroup (sync.WaitGroup) — allows waiting for a group of goroutines to finish.
- Cond (sync.Cond) — a condition variable for notifying goroutines about a certain state.
- Once (sync.Once) — guarantees a function is executed only once.
- Atomic operations (sync/atomic) — for atomic operations on variables without locks.
Example of using Mutex:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
These primitives enable efficient management of concurrent access and synchronization in multi-threaded programs in Go.