What is Mutual Exclusion: Definition and Examples in OS
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.
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}")
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.