Sobes.tech
Middle

What is deadlock and race condition, how to deal with them?

sobes.tech AI

Answer from AI

Deadlock — a situation where multiple goroutines (or threads) block each other, waiting for resources held by others, and ultimately none can continue.

Race condition — a state where the outcome of a program depends on the unpredictable order of goroutine execution, leading to errors or incorrect data.

How to fight:

  • For deadlock:

    • Avoid nested locks.
    • Use timeouts when acquiring mutexes.
    • Design logic so that all goroutines acquire resources in the same order.
  • For race condition:

    • Use synchronization: mutexes, channels.
    • Avoid concurrent access to mutable data without protection.
    • Use tools like the Go race detector (go run -race) to identify races.

Example of race condition:

var counter int

func increment(wg *sync.WaitGroup) {
    defer wg.Done()
    counter++ // unsafe without mutex
}

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 1000; i++ {
        wg.Add(1)
        go increment(&wg)
    }
    wg.Wait()
    fmt.Println(counter) // may be less than 1000 due to races
}

Fix — add a mutex around the modification of counter.