Python threading. How do I lock a thread?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
In Python, you usually do not "lock a thread" directly. What you lock is a shared resource or a critical section so that only one thread can use it at a time.
What a Lock Really Does
A threading.Lock is a synchronization primitive. One thread acquires it, enters the critical section, and later releases it. If another thread reaches the same lock while it is held, that thread waits.
This is how you protect shared state from race conditions.
Without the lock, counter += 1 can interleave unpredictably between threads.
The Right Mental Model
If you say "I want to lock a thread," the real question is usually one of these:
- how do I prevent two threads from editing the same data at once
- how do I pause one thread until another thread finishes something
- how do I ensure only one thread enters a block of code
Those are solved with synchronization primitives, not by freezing a thread object itself.
Basic Lock Usage
The cleanest style is the context-manager form:
Using with lock: is better than manually calling acquire() and release() because it guarantees the release even if an exception happens inside the block.
If you need manual control, you can still write:
Reentrant Locks and Other Primitives
Sometimes a plain Lock is not enough.
Use threading.RLock when the same thread may need to acquire the same lock more than once:
Use a Semaphore when you want to allow a limited number of threads through at once instead of exactly one.
Use an Event when one thread should wait until another thread signals that work is ready.
That is not mutual exclusion, but it is often what people actually mean when they say they want to "lock" a thread.
What About the GIL
Python has a Global Interpreter Lock in CPython, but it does not remove the need for your own locks. The GIL does not make compound operations on your application data magically safe, and it does not coordinate the meaning of your critical sections.
You still need explicit synchronization for shared mutable state.
A Thread-Safe Queue Is Often Better
If threads are passing work to each other, a queue.Queue is often a better design than manually locking your own list.
The queue already handles the internal locking for you.
Common Pitfalls
The biggest pitfall is locking too much code. Keep the critical section as small as possible so threads do not block each other unnecessarily.
Another pitfall is forgetting to release a lock on error. That is why with lock: is the preferred pattern.
A third pitfall is trying to use a lock when the real need is coordination rather than exclusion. In those cases, Event, Condition, or Queue is usually the better tool.
Finally, avoid multiple locks with inconsistent acquisition order unless you are prepared to reason carefully about deadlocks.
Summary
- In Python, you lock shared code or data, not the thread object itself
- '
threading.Lockprotects critical sections from concurrent access' - '
with lock:is the safest and clearest usage pattern' - Use
RLock,Semaphore,Event, orQueuewhen the problem is not simple mutual exclusion - The GIL does not replace proper synchronization in your own program
Related reading
- Python threads all executing on a single core
- Python threads and queue example
- Python time.sleep vs event.wait
- Python Tornado - Asynchronous Request is blocking
- Python truncate a long string
- Python try...except comma vs 'as' in except
- Python Twisted wait for a variable to be filled by another event
- Python what are the advantages of async over threads?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.