What types of data synchronization do you know to prevent race conditions and data races?
sobes.tech AI
Answer from AI
The following synchronization types are used in Go to prevent race conditions and data races:
-
Mutex (sync.Mutex) — a basic primitive for mutual exclusion, blocks access to shared data.
-
RWMutex (sync.RWMutex) — allows multiple readers to read data simultaneously but blocks writing.
-
Atomic operations (sync/atomic) — enable atomic operations on primitive types without locks.
-
Channels (chan) — allow safe data transfer between goroutines, providing synchronization through communication.
-
WaitGroup (sync.WaitGroup) — for waiting for a group of goroutines to finish.
-
Cond (sync.Cond) — a condition variable for more complex synchronization.
Example of using Mutex:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
Using these tools helps avoid data races and ensures correct operation of concurrent programs.