⚙️Mutex (Lock)
Also known as Mutex, Lock, Mutual Exclusion
A lock that lets only one thread at a time touch shared data.
Think of it like
Think of it like the key to a toilet for one. Only the person with the key can go in.
Example
Lucy has two threads that each add 1 to a counter 100,000 times. With a lock around the add, the total is always 200,000.
Why it matters
It is the basic tool to keep shared data right when many threads run at once.
Definition
Example code
python
lock = threading.Lock()
def add():
global count
for _ in range(100000):
with lock: # one thread at a time
count += 1Common mistake
Key takeaways
- 1One at a time. Others wait their turn.
- 2Take, then release. Always let go.
- 3Hold it briefly. Long locks slow everyone.