Junior — Middle
Could you explain the principle of mutual exclusion (Mutex) and its use in multithreaded programs?
sobes.tech AI
Answer from AI
Mutual exclusion (Mutex) is a synchronization mechanism used to prevent multiple threads from simultaneously accessing a shared resource (such as a variable or file). A mutex guarantees that only one thread can own the lock and execute the critical section at any given time.
Working principle:
- A thread attempts to acquire the mutex before entering the critical section.
- If the mutex is free, the thread gains access and continues.
- If the mutex is occupied by another thread, the current thread is blocked and waits for it to be released.
- After finishing with the resource, the thread releases the mutex, allowing other threads to proceed.
In Go, this is implemented using the sync.Mutex type:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock() // acquire mutex
counter++ // critical section
mu.Unlock() // release mutex
}
Using a mutex prevents race conditions and ensures data correctness during parallel execution.