Thread Synchronization & Deadlocks in Python
When multiple threads share and modify the same data, a race condition can occur — two threads changing a value at nearly the same time, producing an incorrect result. A Lock prevents this by allowing only one thread to hold it at a time, forcing others to wait their turn. Used carelessly, though, locks can also cause a deadlock: two threads each waiting forever for a lock the other is holding, with neither able to proceed.
threading.Lock() creates a lock
Initially available for any thread to claim.
.acquire() claims it
Blocking if another thread already holds it, until it’s released.
.release() gives it back
Letting a waiting thread proceed.
with lock: is the safer pattern
Automatically releasing the lock even if an error occurs inside the block.
Deadlocks come from inconsistent lock ordering
Avoiding one generally means always acquiring multiple locks in the same, consistent order.
import threading counter = 0lock = threading.Lock() def increment(): global counter for _ in range(100000): with lock: counter += 1 threads = [threading.Thread(target=increment) for _ in range(2)]for t in threads: t.start()for t in threads: t.join() print(counter)Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.