Middle+
What synchronization methods do you know in Go?
sobes.tech AI
Answer from AI
In Go, the following main tools are used for goroutine synchronization:
- Mutex (sync.Mutex) — a basic primitive for mutual exclusion, blocks access to shared data.
- RWMutex (sync.RWMutex) — an extended mutex that allows multiple readers to read simultaneously but blocks writing.
- WaitGroup (sync.WaitGroup) — allows waiting for a group of goroutines to finish.
- Cond (sync.Cond) — a conditional variable for notifying goroutines about an event.
- Atomic operations (sync/atomic) — for safely modifying variables without locks.
- Channels (chan) — the idiomatic way to synchronize and pass data between goroutines.
Example of using Mutex:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
Channels allow synchronizing execution and exchanging data:
ch := make(chan int)
go func() {
ch <- 42 // send value
}()
val := <-ch // receive value