Python threading
Python threads
threading pitfalls
concurrent programming
Python concurrency

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.

Browse interview questions

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:

python
1import threading
2import time
3
4def worker(name):
5    print(f"{name} starting")
6    time.sleep(1)
7    print(f"{name} done")
8
9t = threading.Thread(target=worker, args=("job-1",))
10t.start()
11t.join()

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.

python
1import threading
2
3counter = 0
4
5def increment():
6    global counter
7    for _ in range(100000):
8        counter += 1
9
10threads = [threading.Thread(target=increment) for _ in range(2)]
11for t in threads:
12    t.start()
13for t in threads:
14    t.join()
15
16print(counter)

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:

python
1import threading
2
3counter = 0
4lock = threading.Lock()
5
6def increment():
7    global counter
8    for _ in range(100000):
9        with lock:
10            counter += 1

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:

python
1import queue
2import threading
3
4q = queue.Queue()
5
6def producer():
7    for i in range(5):
8        q.put(i)
9
10def consumer():
11    while True:
12        item = q.get()
13        print(item)
14        q.task_done()
15        if item == 4:
16            break

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 asyncio or 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.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No 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 course
Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions