Avoid race conditions in Go by protecting shared memory access with synchronization primitives like sync.Mutex or sync.RWMutex. Use a mutex to lock before reading or writing shared data and unlock immediately after the operation completes.
var (
mu sync.Mutex
count int
)
func increment() {
mu.Lock()
count++
mu.Unlock()
}
For read-heavy workloads, use sync.RWMutex to allow multiple readers but exclusive writers:
var mu sync.RWMutex
func read() {
mu.RLock()
_ = count
mu.RUnlock()
}
func write() {
mu.Lock()
count++
mu.Unlock()
}