Middle+
What is a race condition and how to avoid it?
sobes.tech AI
Answer from AI
Race condition is a situation in multithreaded or concurrent programs where multiple threads or goroutines access and modify shared data simultaneously without proper synchronization. This leads to unpredictable behavior and errors.
To avoid race conditions in Go, synchronization mechanisms are used:
- Mutex (sync.Mutex) — blocks access to a shared resource, allowing only one thread to work with it at a time.
- Channel — provides safe data exchange between goroutines.
- Atomic operations (sync/atomic) — for simple operations on variables.
Example with mutex:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
This approach guarantees that changes to the counter variable are sequential and will not lead to a race condition.