Mutex Locks with threading.Lock
A mutex lock (`threading.Lock`) ensures only one thread executes a critical section at a time. Use `with lock:` context managers to guarantee locks release even on errors 🔒.
import threading
lock = threading.Lock()
safe_counter = 0
def safe_add():
global safe_counter
with lock: # Acquires lock, executes, releases automatically 🔒
safe_counter += 1
threads = [threading.Thread(target=safe_add) for _ in range(5)]
for t in threads: t.start()
for t in threads: t.join()
print(f"Final Count: {safe_counter} ✅")
# 52. Mutex Locks with threading.Lock A mutex lock (`threading.Lock`) ensures only one thread executes a critical section at a time. Use `with lock:` context managers to guarantee locks release even on errors 🔒. ```python import threading lock = threading.Lock() safe_counter = 0 def safe_add(): global safe_counter with lock: # Acquires lock, executes, releases automatically 🔒 safe_counter += 1 threads = [threading.Thread(target=safe_add) for _ in range(5)] for t in threads: t.start() for t in threads: t.join() print(f"Final Count: {safe_counter} ✅") ``` Always use `with lock:` instead of manual `lock.acquire()` and `lock.release()`. If an exception occurs, `with` guarantees the lock is released, avoiding permanent freezes! 🔒 --- ### Question What is the primary benefit of using `with lock:` instead of `lock.acquire()`? 🧠- [ ] a. Guarantees the lock is released even if an unhandled exception is raised 🔒 - [ ] b. Makes Python execute the block on GPU cores - [ ] c. Doubles the execution speed of mathematical loops - [ ] d. Disables all other operating system background processes --- ### Challenge Create a `threading.Lock()` and a variable `val = 0`. Inside `with lock:`, increment `val += 5`. Print `val`. 🎯 <details> <summary>Solution</summary> ```python import threading lock = threading.Lock() val = 0 with lock: val += 5 print(val) ``` </details>