Introduction
Imagine two people trying to use the same key to open a door at the same time. Without a way to take turns, they might get stuck or cause confusion. Mutex locks solve this problem by making sure only one person can use the key at once.
Imagine a single bathroom in a house shared by several people. Only one person can use it at a time. When someone is inside, others wait outside until it is free. This way, everyone gets a turn without confusion or accidents.
┌───────────────┐
│ Shared Resource│
│ (Locked) │
└──────┬────────┘
│
┌───▼────┐
│ Process │
│ A holds│
│ the lock│
└─────────┘
│
┌───▼────┐ Waiting
│ Process │─────────┐
│ B │ │
└─────────┘ │
│
┌─────────┐ │
│ Process │<────────┘
│ C │ Waiting
└─────────┘import threading # Shared resource counter = 0 # Mutex lock lock = threading.Lock() def increment(): global counter for _ in range(100000): lock.acquire() counter += 1 lock.release() threads = [] for _ in range(5): t = threading.Thread(target=increment) threads.append(t) t.start() for t in threads: t.join() print(f"Final counter value: {counter}")