How do threads work in Python, and what are common Python-threading specific pitfalls?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Python threads are real operating-system threads managed through the threading module, but in standard CPython they do not execute Python bytecode in true parallel on multiple cores because of the Global Interpreter Lock, or GIL. That makes threads useful mainly for I/O-bound work, while CPU-bound work often needs multiprocessing or native extensions instead.
Basic thread lifecycle in Python
A thread runs a callable in parallel with the main thread from the program's point of view:
start() asks the thread to begin. join() waits for it to finish. Without join(), the main program may continue before the worker is done.
The GIL changes what "parallel" means
In CPython, only one thread executes Python bytecode at a time because of the GIL. That means threads are not the usual tool for speeding up CPU-heavy pure Python loops.
They are still useful when threads spend time waiting on:
- network I/O
- file I/O
- database calls
- sleeps or blocking library calls
While one thread waits, another can run. That is why threading helps I/O-bound programs even with the GIL.
Shared memory makes communication easy and bugs easy
Threads share the same process memory. That is convenient because you can pass references to normal Python objects, but it also creates race conditions.
This may not produce the value you expect because counter += 1 is not an atomic high-level operation.
Use locks for shared mutable state
When multiple threads mutate shared state, use a lock:
Locks solve many correctness problems, but they also introduce complexity. The more shared mutable state you have, the harder threaded code becomes to reason about.
Queues are often better than ad hoc sharing
For producer-consumer patterns, queue.Queue is usually better than raw shared lists or dictionaries:
Queues reduce the need for manual locking and make thread communication clearer.
Common Python-threading pitfalls
A few traps show up repeatedly:
- assuming threads speed up CPU-bound Python code
- forgetting to
join()and then wondering why output is incomplete - mutating shared objects without synchronization
- acquiring multiple locks in inconsistent order and causing deadlocks
- mixing daemon threads with important shutdown work and losing data on exit
The daemon-thread point is especially subtle: daemon threads are killed when the program exits, so they are not appropriate for work that must finish cleanly.
Threading is not the only concurrency tool
If the problem is CPU-bound, prefer:
- '
multiprocessing' - '
concurrent.futures.ProcessPoolExecutor'
If the problem is high-volume async I/O, prefer:
- '
asyncio'
Threading is one concurrency tool, not the default answer to every parallel-looking problem.
Common Pitfalls
- Expecting Python threads to speed up CPU-heavy pure Python code.
- Forgetting that shared mutable state creates race conditions.
- Using locks carelessly and creating deadlocks.
- Skipping
join()when the main thread needs deterministic completion. - Reaching for threads when
asyncioor multiprocessing would fit the workload better.
Summary
- Python threads are OS threads, but the CPython GIL limits parallel Python bytecode execution.
- Threads are most useful for I/O-bound tasks, not CPU-bound pure Python work.
- Shared memory is convenient, but it makes race conditions possible.
- Locks and queues are the main building blocks for safe threaded coordination.
- Choose threading, multiprocessing, or async I/O based on the actual workload, not habit.
Related reading
- How do two or more threads share memory on the heap that they have allocated?
- How do we use runOnUiThread in Android?
- How do you correctly await multiple asynchronous methods in dart?
- How do you create a daemon in Python?
- How do we determine the number of days for a given month in python
- How do you access the query string in Flask routes?
- How do you create custom asynchronous functions in node.js?
- How do you get tkinter to work with asyncio?
System design interview problems on this topic
- Design a Distributed Locking System: solution and walkthrough
- Design a Distributed Counter: solution and walkthrough
- Design Ticketmaster: solution and walkthrough
- Design a Flash Sale System: solution and walkthrough
.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 courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseInterview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.