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}")
mutex lock in operating systems?mutex.lock() shared_counter = shared_counter + 1 mutex.unlock()If two threads run this code simultaneously starting with
shared_counter = 5, what is the final value of shared_counter?mutex.unlock() use_shared_resource() mutex.lock()What is the main problem with this code?
mutex.unlock() before any mutex.lock(), which is incorrect because you cannot release a lock you don't hold.Pass the test and this pattern moves unknown