Sobes.tech
Middle+

How to fix race condition code so that it works deterministically?

sobes.tech AI

Answer from AI

A race condition occurs when multiple goroutines (threads) access shared data simultaneously without proper synchronization, leading to unpredictable program behavior.

To fix the code and make it deterministic, synchronization mechanisms should be used:

  • Mutex (sync.Mutex) — locks access to shared data, allowing only one goroutine to work with it at a time.
  • Channel — for data transfer between goroutines, which avoids shared access.
  • sync.WaitGroup — to wait for goroutines to finish.

Example of fixing with a mutex:

package main

import (
	"fmt"
	"sync"
)

func main() {
	var mu sync.Mutex
	counter := 0
	var wg sync.WaitGroup

	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			mu.Lock()
			counter++
			mu.Unlock()
		}()
	}

	wg.Wait()
	fmt.Println("Counter:", counter)
}

In this example, the mutex ensures that the counter increment happens sequentially, preventing race conditions and ensuring a deterministic result.