Principal
Why does adding a mutex only for writing not solve the data race problem? How to correctly use a mutex to protect a shared variable?
sobes.tech AI
Answer from AI
Adding a mutex only for writing does not solve the data race problem because:
- If reading occurs without locking, it may get partially updated or inconsistent data if another goroutine or thread is performing a write at that moment.
- A data race occurs when there is concurrent access to a shared variable, with at least one access being a write, and proper synchronization is absent.
Proper use of mutex to protect a shared variable:
- Lock the mutex during both reading and writing. This guarantees that reading does not happen simultaneously with writing.
- During writing, lock the mutex, modify the data, then unlock the mutex.
- During reading, also lock the mutex, read the data, then unlock the mutex.
Example in Swift:
let mutex = DispatchSemaphore(value: 1)
var sharedData = 0
func writeData(newValue: Int) {
mutex.wait()
sharedData = newValue
mutex.signal()
}
func readData() -> Int {
mutex.wait()
let value = sharedData
mutex.signal()
return value
}
Thus, the mutex provides mutual exclusion and prevents race conditions when accessing a shared variable.