Sub topic 3
Running tasks in threads
This chapter covers how to start, wait for, and stop threads with the threading module. It assumes you can write Python functions and scripts and use with statements. It also assumes you know the idea of a program doing several things at once. It does not cover locks, the GIL, or pools. Those have their own chapters, and this one points to them where they matter.
What a thread is
A thread is a separate path of execution inside one process. All threads in a process share the same memory. They see the same global variables, the same module objects, and the same open files. Each thread has its own call stack, so each has its own local variables and its own position in the code.
A Python program always starts with one thread, the main thread. The threading module lets you create more. Each new thread runs one function, called the target, and ends when that function returns or raises.
Threads are cheap compared to processes. They start quickly and need no copying of data to share it. The price of shared memory is that threads can interfere with each other, which a later chapter covers.
Starting and joining a thread
Creating a threading.Thread object does not run anything. You call start() to launch the thread. You call join() to wait for it to finish.
import threading
import time
def greet(name, delay):
me = threading.current_thread().name
print(f"{me}: hello {name}")
time.sleep(delay)
print(f"{me}: done with {name}")
t1 = threading.Thread(target=greet, args=("Ada", 0.2), name="worker-1")
t2 = threading.Thread(target=greet, args=("Grace", 0.1), name="worker-2")
t1.start()
t2.start()
print("main: threads started, main keeps running")
t1.join()
t2.join()
print("main: all threads finished")The order of the first lines can change from run to run. start() returns immediately, so the main thread may print before either worker does. The operating system decides which thread runs when, and your code cannot rely on that order. The only ordering you can count on is the one you create yourself, such as join() returning only after the target has finished.
The lifecycle of a thread object has three stages:
A thread object can be started only once. Calling start() a second time raises RuntimeError. If you need the same work again, build a new Thread.
Passing arguments and getting results back
args is a tuple of positional arguments and kwargs is a dictionary of keyword arguments. Two mistakes are common here:
- Writing
args=("Ada"). The parentheses alone do not make a tuple. You needargs=("Ada",). - Writing
target=greet("Ada", 0.2). That calls the function in the current thread and passes its return value (None) as the target. Pass the function itself, without parentheses.
The return value of the target is discarded. join() returns None, so a plain thread has no built-in way to hand back a result. The simplest safe pattern is to give each thread its own slot in a shared list.
import threading
import time
def square(index, results):
time.sleep(0.1) # stands in for real work
results[index] = index * index
results = [None] * 5
threads = [
threading.Thread(target=square, args=(i, results))
for i in range(5)
]
for t in threads:
t.start()
for t in threads:
t.join()
print(results) # [0, 1, 4, 9, 16]Each thread writes to a different index, so no two threads touch the same slot. That is why this needs no lock. If several threads update the same variable, the situation changes, and the next chapter covers it. When you want results and error handling without managing slots yourself, a pool is usually a better fit. That comes later too.
Naming, identifying, and inspecting threads
Useful tools for seeing what your threads are doing:
threading.current_thread()returns theThreadobject of the code that is running now. Its.nameis a label you can set with thename=argument. Without one, Python assigns a name such asThread-1 (greet).threading.main_thread()returns the main thread.threading.active_count()returns how many threads are alive, including the main thread.threading.enumerate()returns a list of the liveThreadobjects.t.is_alive()returnsTruebetweenstart()and the end of the target.
Give threads meaningful names. They appear in logging output when you include %(threadName)s in the format, and they make debugging much easier.
Waiting with a timeout
join() blocks until the thread ends. With a timeout, t.join(timeout=2.0) waits at most two seconds and then returns whether or not the thread has finished. It does not tell you which happened. Check is_alive() afterward:
import threading
import time
def slow():
time.sleep(3)
t = threading.Thread(target=slow, name="slow-1")
t.start()
t.join(timeout=0.5)
if t.is_alive():
print("still running after 0.5 seconds")
else:
print("finished in time")
t.join() # wait for it properly before the script endsA timeout only stops your waiting. It does not stop the thread.
Daemon threads
By default Python waits for every non-daemon thread to finish before the program exits. A daemon thread is a background thread that does not hold the program open. When only daemon threads remain, the interpreter exits and they are stopped abruptly.
import threading
import time
def heartbeat():
while True:
print("heartbeat")
time.sleep(0.5)
t = threading.Thread(target=heartbeat, daemon=True)
t.start()
time.sleep(1.2)
print("main exits; the daemon thread dies with it")You must set daemon=True before calling start(). Setting it afterward raises RuntimeError.
Stopping a thread cooperatively
Python has no supported way to kill a thread from outside. The reliable approach is for the thread to check a signal and exit on its own. threading.Event is the standard signal. It holds a flag that starts false. set() makes it true, is_set() reads it, and wait(timeout) sleeps until the flag is set or the timeout passes.
import threading
import time
def ticker(stop):
n = 0
while not stop.is_set():
n += 1
print("tick", n)
stop.wait(0.2) # sleeps, but wakes at once if stop is set
stop = threading.Event()
t = threading.Thread(target=ticker, args=(stop,), name="ticker")
t.start()
time.sleep(0.7)
stop.set()
t.join()
print("ticker stopped cleanly")This prints about four ticks. Using stop.wait(0.2) instead of time.sleep(0.2) matters. The thread reacts to set() immediately instead of finishing its sleep first. For a worker that loops over blocking calls, make sure each call has a timeout. Otherwise the thread cannot notice the signal.
What happens when a thread raises
An uncaught exception ends only the thread that raised it. The traceback is printed to standard error, and the main thread carries on as if nothing happened. This is a common source of silent failures: the program keeps running but a worker is gone.
You can observe these failures by replacing threading.excepthook:
import threading
def risky():
raise ValueError("boom")
def on_thread_error(args):
print(f"{args.thread.name} failed: "
f"{args.exc_type.__name__}: {args.exc_value}")
threading.excepthook = on_thread_error
t = threading.Thread(target=risky, name="risky-1")
t.start()
t.join()
print("main is still running")The hook receives an object with exc_type, exc_value, exc_traceback, and thread. In real programs you would log the error or record it so the main thread can react. A simpler alternative is to catch exceptions inside the target and store them next to the result.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The work runs before `start()` and nothing runs in parallel | `target=f()` was written instead of `target=f` | Pass the function without calling it |
| `TypeError` about argument counts or types | `args=("x")` is a string, not a tuple | Write `args=("x",)` |
| `RuntimeError: threads can only be started once` | `start()` was called twice on one object | Create a new `Thread` |
| The program never exits | A non-daemon thread loops forever | Signal it with an `Event` and `join()` it |
| Output is cut short at exit | The thread was a daemon and was stopped | Join the thread before the program ends |
| A worker disappears and no one notices | An exception ended the thread | Catch errors in the target or set `threading.excepthook` |
| Results come back in a different order each run | Scheduling is not deterministic | Store results by index, or sort afterward |
Where threads fit
Threads are a good match when tasks spend most of their time waiting, for example on a network reply or a disk read. While one thread waits, others make progress. Whether threads also speed up computation depends on the Global Interpreter Lock, which later chapters explain along with the I/O-bound and CPU-bound distinction. For now, treat threads as a way to overlap waiting, and measure before assuming they help.
Exercise
A script starts three threads with Thread(target=work, args=(i,)) for i in 0, 1, 2 and then prints "done" without calling join(). Sometimes "done" appears before the workers finish. Why, and what is the smallest change that guarantees "done" prints last?
Show answer
start() returns immediately, and the main thread does not wait for the workers unless told to. The workers are non-daemon, so the program still waits for them at exit, but the main thread's print("done") can run earlier. Keep the thread objects in a list and call t.join() on each one before printing "done".
Exercise
A background thread runs while True: process(queue_item) with daemon=True, and it writes to a file. Users report that the last few records are sometimes missing after the program exits. What is the cause, and how would you redesign the thread to stop safely?
Show answer
At interpreter exit, daemon threads are stopped abruptly, so buffered or in-progress writes can be lost and finally or with cleanup may not run. Make the thread non-daemon, have its loop check a threading.Event (using timeouts on blocking calls), call set() on the event at shutdown, and join() the thread so it finishes its work and closes the file.