Coding

Threading in Python: Basics, Locks and ThreadPoolExecutor

Threading in Python means creating threading.Thread objects that run a function concurrently with the rest of your program: pass the function as target, call start(), then join() to wait for it. Threads work best for I/O-bound tasks such as network requests, because in standard CPython only one thread runs Python bytecode at a time.

import threading

def greet(name):
    print(f"Hello, {name}")

worker = threading.Thread(target=greet, args=("Alex",))
worker.start()
worker.join()

That is the whole pattern. The rest of this article covers what happens around it: several threads at once, sharing data without corrupting it, stopping threads, thread pools, and when threads are the wrong tool.

How to create and start a thread in Python

The constructor is threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, daemon=None). The docs say it "should always be called with keyword arguments". The useful ones are:

  • target: the callable to run. If it is None, nothing runs.
  • args: a tuple or list of positional arguments. A single argument needs a trailing comma, as in ("Alex",).
  • kwargs: a dictionary of keyword arguments.
  • name: a label used for identification only. It has no other meaning, and two threads may share a name.
  • daemon: whether the thread is a daemon. If you leave it as None, it is inherited from the thread that creates it.

Creating the object does not run anything. start() does, and it may be called at most once per thread object. A second call raises RuntimeError. If you need to run the same work again, create a new Thread.

How to run several threads and wait for them

Start every thread first, then join them all. If you start and join inside the same loop iteration, each thread finishes before the next begins, and you get no concurrency.

import threading
import time

def slow_task(task_id):
    name = threading.current_thread().name
    time.sleep(1)
    print(f"task {task_id} finished in {name}")

threads = [
    threading.Thread(target=slow_task, args=(task_id,), name=f"worker-{task_id}")
    for task_id in range(3)
]

for thread in threads:
    thread.start()

for thread in threads:
    thread.join()

print("all done")

Example output (the order of the first three lines can differ between runs):

task 0 finished in worker-0
task 1 finished in worker-1
task 2 finished in worker-2
all done

The three one-second sleeps overlap, so the program takes about one second rather than three. time.sleep() stands in for any wait on the outside world, such as a download or a database call.

join(timeout=None) blocks the calling thread until the other thread ends, "either normally or through an unhandled exception". With a timeout, join() still returns None, so you have to call is_alive() afterwards to find out whether it timed out:

worker.join(timeout=5)
if worker.is_alive():
    print("still running after 5 seconds")

Joining the current thread raises RuntimeError because it would deadlock, and so does joining a thread that has not been started yet.

How the GIL limits threading in Python

The global interpreter lock (GIL) is the mechanism CPython uses so that only one thread executes Python bytecode at a time. The Python glossary describes the trade-off: it makes the object model, including built-in types such as dict, implicitly safe against concurrent access, "at the expense of much of the parallelism afforded by multi-processor machines".

Two details decide when threads help:

  • The GIL is always released while doing I/O. While one thread waits on a socket or a file, another can run Python code.
  • Some extension modules release the GIL during heavy work such as compression or hashing, so those calls can overlap across threads.

The consequence, in the words of the threading docs: threading "is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously", but the GIL "limits the performance gains of threading when it comes to CPU-bound tasks". For pure-Python number crunching, the docs advise multiprocessing or concurrent.futures.ProcessPoolExecutor instead.

As of Python 3.13, free-threaded builds can disable the GIL (see PEP 703), but the docs state this is not available by default. Check how your interpreter was built before assuming threads run in parallel. If you are weighing threads against hardware, the hardware side of the word is covered in CPU cores vs threads; that is a different concept from Python's Thread objects.

How to share data between threads safely with a Lock

Threads share memory, so two threads can read and change the same variable. An operation like counter += 1 is a read, an add and a write, and a thread switch can land between those steps. Updates can then be lost. A threading.Lock lets only one thread at a time into a block of code:

import threading

counter = 0
counter_lock = threading.Lock()

def add_many(times):
    global counter
    for _ in range(times):
        with counter_lock:
            counter += 1

threads = [threading.Thread(target=add_many, args=(100_000,)) for _ in range(4)]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()

print(counter)

With the lock, the result is always 400000. Remove the with counter_lock: line and the total may come out lower on some runs and Python versions, which is what makes this kind of bug hard to reproduce.

Use with lock: rather than calling acquire() and release() by hand. Per the docs, acquire is called when the block is entered and release when it is exited, even if the block raises an exception. That is equivalent to wrapping the block in try and finally.

Keep the locked section short. A thread that holds a lock while it waits on the network blocks every other thread that needs the lock.

How to stop a thread cleanly

There is no method to kill a thread. The documented approach is to make the thread check a threading.Event, an object that holds a flag which is initially false. set() turns it true, clear() resets it, and wait(timeout) blocks until the flag is true. wait() returns True if the flag was set and False if the timeout expired first, which makes it a better sleep for a loop that must stay responsive:

import threading

stop_requested = threading.Event()

def poll_forever():
    while not stop_requested.is_set():
        print("checking...")
        stop_requested.wait(2.0)

worker = threading.Thread(target=poll_forever)
worker.start()

# later, from the main thread
stop_requested.set()
worker.join()

Here wait(2.0) pauses for up to two seconds but returns the moment set() is called, so the thread exits promptly instead of finishing a long time.sleep() first.

What daemon threads do

A daemon thread is flagged so that "the entire Python program exits when only daemon threads are left". Set it with daemon=True in the constructor, or assign thread.daemon = True before start(). Setting it after the thread has started raises RuntimeError.

The docs add a warning: daemon threads are stopped abruptly at shutdown, so open files and database transactions may not be released properly. If you want threads to stop gracefully, make them non-daemonic and signal them with an Event, as above. Reserve daemon threads for background work that is safe to cut off, such as a heartbeat.

ThreadPoolExecutor: the easier way to use threads

For a batch of independent tasks, concurrent.futures.ThreadPoolExecutor is simpler than managing Thread objects. The docs describe it as a higher-level interface that pushes tasks to background threads while letting you collect their results. Using the executor in a with block shuts it down and waits for the work to finish.

from concurrent.futures import ThreadPoolExecutor, as_completed
import time

def fetch(item):
    time.sleep(1)  # stand-in for a network call
    return item * 2

with ThreadPoolExecutor(max_workers=5) as executor:
    futures = {executor.submit(fetch, item): item for item in range(5)}
    for future in as_completed(futures):
        item = futures[future]
        try:
            print(item, "->", future.result())
        except Exception as error:
            print(item, "failed:", error)

submit(fn, *args) schedules the call and returns a Future. future.result() returns the value, or raises the exception the function raised, so errors surface in the thread that asks for the result. If you only need the results in input order, executor.map(fetch, range(5)) works like the built-in map(), except the calls may run concurrently.

If you leave out max_workers, Python 3.13 uses min(32, (os.process_cpu_count() or 1) + 4). The docs say this keeps at least 5 workers for I/O-bound tasks while avoiding very large resource use on many-core machines. Earlier versions used a different formula, so set the number yourself if your code must behave the same everywhere.

Which to use: threads, processes or a pool

SituationUseWhy
Many network or disk waitsThreadPoolExecutorThe GIL is released during I/O, so waits overlap.
One background job, such as a timer or pollerthreading.Thread with an EventDirect control over start and stop.
CPU-heavy pure-Python workProcessPoolExecutorEach process has its own GIL, but arguments and results must be picklable.
Heavy work inside a library that releases the GILThreads can workCompression and hashing modules may release the GIL, per the glossary.

Common threading mistakes

  • Passing the result of the call instead of the function. Thread(target=greet("Alex")) runs greet immediately in the main thread and passes its return value (usually None) as the target. Write Thread(target=greet, args=("Alex",)).
  • Calling run() instead of start(). run() executes the target in the current thread, with no concurrency.
  • Joining inside the start loop. This serializes the work, as described above.
  • Expecting results from a plain thread. The return value of target is discarded. Use a queue.Queue, a shared list guarded by a lock, or a ThreadPoolExecutor future to get results back.
  • Relying on output order. Threads finish in whatever order the scheduler allows. If order matters, collect results and sort them, or use executor.map.

Frequently asked questions

Does threading in Python make code run in parallel?
Not for Python code in the standard CPython build. Because of the Global Interpreter Lock, only one thread can execute Python bytecode at a time. Threads still help with I/O-bound work such as network calls, because the GIL is released while waiting on I/O. For CPU-bound work, the Python docs advise multiprocessing or ProcessPoolExecutor.
What is the difference between a thread and a process in Python?
Threads run inside one process and share its memory, so they can read and change the same objects, which is why locks are needed. Processes have separate memory and, with multiprocessing, each has its own interpreter and GIL. Passing data between processes means it has to be picklable.
Why does my Python program not exit after the main code finishes?
The program waits for all non-daemon threads to finish. If a thread is still running a loop, the process stays alive. Make the thread stop by checking a threading.Event, or mark it as a daemon thread, keeping in mind that daemon threads are stopped abruptly at shutdown.
Can I stop a thread from outside in Python?
The threading module has no method to kill a thread. The documented approach is to make threads non-daemonic and signal them with an Event that the thread checks regularly, then join the thread.

Sources