0
0
Operating-systemsConceptBeginner · 3 min read

What is Mutual Exclusion: Definition and Examples in OS

In operating systems, mutual exclusion is a technique to prevent multiple processes or threads from accessing a shared resource at the same time. It ensures that only one process can use the resource, avoiding conflicts and data corruption.
⚙️

How It Works

Mutual exclusion works like a traffic light at a single-lane bridge. Only one car can cross at a time to avoid crashes. Similarly, when multiple processes want to use the same resource, mutual exclusion allows only one to enter the critical section where the resource is accessed.

This is usually done by using locks or flags. When a process wants to use the resource, it must first acquire the lock. If the lock is already taken, the process waits until it is free. Once done, the process releases the lock so others can use the resource safely.

💻

Example

This example shows two threads trying to increase a shared counter. Using a lock ensures only one thread changes the counter at a time, preventing errors.

python
import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter
    for _ in range(100000):
        with lock:
            counter += 1

thread1 = threading.Thread(target=increment)
thread2 = threading.Thread(target=increment)

thread1.start()
thread2.start()

thread1.join()
thread2.join()

print(f"Final counter value: {counter}")
Output
Final counter value: 200000
🎯

When to Use

Use mutual exclusion whenever multiple processes or threads share resources like files, memory, or devices. It prevents data corruption and unpredictable behavior.

Common real-world cases include:

  • Accessing a shared file to write data
  • Updating a bank account balance in a multi-user system
  • Controlling access to hardware devices like printers

Key Points

  • Mutual exclusion prevents simultaneous access to shared resources.
  • It uses locks or similar mechanisms to control access.
  • Without it, data corruption or crashes can occur.
  • It is essential in concurrent programming and operating systems.

Key Takeaways

Mutual exclusion ensures only one process accesses a shared resource at a time.
It prevents conflicts and data corruption in concurrent systems.
Locks are a common way to implement mutual exclusion.
Use mutual exclusion when multiple threads or processes share data or devices.