Learn Python
>>> advanced_python.thread_synchronization

Thread Synchronization & Deadlocks in Python

#concept

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.

#how it works
1

threading.Lock() creates a lock

Initially available for any thread to claim.

2

.acquire() claims it

Blocking if another thread already holds it, until it’s released.

3

.release() gives it back

Letting a waiting thread proceed.

4

with lock: is the safer pattern

Automatically releasing the lock even if an error occurs inside the block.

5

Deadlocks come from inconsistent lock ordering

Avoiding one generally means always acquiring multiple locks in the same, consistent order.

#example
import threading
 
counter = 0
lock = 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)
Output
200000
1Two threads both run increment(), each trying to add 1 to counter 100,000 times.
2Without the lock, both threads could read the same value of counter at nearly the same instant and both write back the same incremented result, silently losing an update.
3with lock: ensures only one thread modifies counter at a time, so every single increment is correctly applied.
4The final result is exactly 200,000 — precisely correct, thanks to the lock preventing any race condition between the two threads.
#use cases
Protecting a shared counter, cache, or data structure that multiple threads read and write
Preventing a race condition that would otherwise cause an intermittent, hard-to-reproduce bug
Coordinating access to a shared resource, like a single database connection used by several threads
Recognizing the risk of deadlock when a program needs to hold more than one lock at a time

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.