Sobes.tech
Middle+

Live coding: a task on goroutines — concurrent access to shared data, race condition, solution via mutex. The difference between sync.Mutex and sync.RWMutex.

sobes.tech AI

Answer from AI

In Go, concurrent access to shared data can lead to a race condition — a situation where multiple goroutines read and write data simultaneously, causing unpredictable behavior.

To address this, mutexes from the sync package are used:

  • sync.Mutex — a simple mutex that blocks access to a resource for all other goroutines while it is held.
  • sync.RWMutex — an extended mutex with separate locks for reading and writing:
    • Multiple goroutines can hold a read lock (RLock) simultaneously if there is no active write.
    • Write (Lock) is exclusive, blocking both reads and other writes.

Example with sync.Mutex:

var mu sync.Mutex
var counter int

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

Example with sync.RWMutex:

var rwMu sync.RWMutex
var data int

func readData() int {
    rwMu.RLock()
    defer rwMu.RUnlock()
    return data
}

func writeData(val int) {
    rwMu.Lock()
    defer rwMu.Unlock()
    data = val
}

Using RWMutex is efficient when read operations significantly outnumber write operations, as it allows multiple reads to occur in parallel without blocking each other.

Live coding: a task on goroutines — concurrent access… - sobes.tech