Junior — Middle
Explain what a lock is in the context of a mutex and what it is used for?
sobes.tech AI
Answer from AI
Lock — is a synchronization mechanism used to prevent multiple threads or goroutines from accessing a shared resource simultaneously, to avoid race conditions and ensure data correctness.
In the context of a mutex, locking means that when one thread acquires (locks) the mutex, other threads trying to acquire the same mutex will wait until the first thread releases (unlocks) it.
Example in Go:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock() // acquire lock
counter++ // critical section
mu.Unlock() // release lock
}
Thus, locking guarantees that only one thread executes the critical section of code at a specific moment.