Sobes.tech
Middle

How can data race conditions be avoided? How does Mutex work?

sobes.tech AI

Answer from AI

Data races occur when multiple goroutines access a shared resource simultaneously for reading and writing without synchronization, leading to unpredictable results.

To prevent data races in Go, synchronization mechanisms such as sync.Mutex are used. A mutex (mutual exclusion) is a primitive that ensures only one goroutine executes in a critical section of code at a time.

Principle of Mutex operation:

  • Before accessing a shared resource, a goroutine calls Lock(), blocking the mutex.
  • If the mutex is already locked, the goroutine waits for it to be released.
  • After finishing with the resource, Unlock() is called to release the mutex.

Example of using Mutex in Go:

import (
    "fmt"
    "sync"
)

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

    increment := func() {
        mu.Lock()
        defer mu.Unlock()
        counter++
    }

    var wg sync.WaitGroup
    for i := 0; i < 1000; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            increment()
        }()
    }
    wg.Wait()
    fmt.Println("Counter:", counter)
}

Thus, using Mutex prevents concurrent access to shared data and avoids races.

How can data race conditions be avoided? How does… - sobes.tech