How to Avoid Race Conditions in Go

Prevent Go race conditions by using sync.Mutex or sync.RWMutex to lock shared variables during read or write operations.

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()
}