Middle
What is a race condition and how to deal with it in Go?
sobes.tech AI
Answer from AI
Race condition — is a situation where multiple goroutines access shared data simultaneously without synchronization, leading to unpredictable behavior and errors.
In Go, this is addressed by the following methods:
- Using mutexes (sync.Mutex) to lock access to shared resources:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
- Using channels to pass data between goroutines, avoiding shared access to variables:
ch := make(chan int)
go func() {
ch <- 1 // send value
}()
val := <-ch // receive value
- Using the sync/atomic package for atomic operations on variables.
It is always important to control access to shared data to avoid race conditions and ensure program correctness.