What is mutual exclusion?
Answer
Mutual exclusion (mutex) ensures that only ONE thread/process can access a critical section (shared resource) at a time. When one process is executing in the critical section, no other process can enter its critical section — this prevents race conditions. Critical section problem: code that accesses shared data and must be executed atomically — concurrent access leads to data corruption. Requirements for solution: (1) Mutual exclusion — only one process in critical section; (2) Progress — if no process is in critical section and some want to enter, selection can't be postponed indefinitely; (3) Bounded waiting — a bound on how many times others can enter before a waiting process gets its turn. Mutex lock (implementation): // Acquire mutex before entering critical section: acquire(mutex); // CRITICAL SECTION -- only one thread here! shared_counter++; // Release mutex after exiting: release(mutex);. Spinlock: busy-waits (spins in a loop checking the lock) until available. Good for short critical sections on multiprocessors — no context switch overhead. Wastes CPU if held long. Blocking mutex: puts the thread to sleep if lock unavailable, woken up when released. Better for long critical sections. Issues with mutexes: deadlock (two threads each holding one lock, waiting for the other); priority inversion (high-priority thread waits for low-priority thread holding a mutex); starvation; performance bottleneck if heavily contended.