Part 13 / Topic 2 of 11
Threads
A thread runs a function in the background while the rest of your program carries on. You make one with threading.Thread(target=function, args=(...)), start it with .start(), and wait for it to finish with .join().
Like a tea stall owner who puts three pots on the stove at once instead of waiting for each one to boil.
import threading
import time
def make_drink(drink: str, seconds: float) -> None:
time.sleep(seconds) # waiting for the water to boil
print("done", drink)
threads = []
for drink in ["chai", "coffee"]:
thread = threading.Thread(target=make_drink, args=(drink, 0.1))
thread.start() # runs in the background from now on
threads.append(thread)
for thread in threads:
thread.join() # wait until it has finished
print("all served")
# done chai (these two lines can swap: both finish at about the same time)
# done coffee
# all served
| Piece | Meaning |
|---|---|
target=make_drink |
The function to run (no (): pass the function, don't call it) |
args=("chai", 0.1) |
A tuple of positional arguments; one argument needs a comma: args=("chai",) |
kwargs={"drink": "chai"} |
Keyword arguments, as a dict |
.start() |
Begin running. Call it once per thread |
.join() |
Wait for the thread to end. Forget it and your program may print results too early |
.is_alive() |
True while the thread is still running |
Daemon threads
Normally Python waits for all threads to end before the program exits. A daemon thread is a background helper that is simply stopped when the main program ends. Use it for "run forever" helpers like a clock or a server.
import threading
import time
def heartbeat() -> None:
while True: # never ends on its own
time.sleep(1)
helper = threading.Thread(target=heartbeat, daemon=True)
helper.start()
print("main program ends now; the daemon is stopped with it")
# main program ends now; the daemon is stopped with it
Without daemon=True, this program would never exit. Don't use daemon threads for work that must finish (like saving a file): they can be stopped in the middle.
Full program: examples/01_threads_basics.py (3 orders one by one ~1.5 s vs with threads ~0.5 s, kwargs, name, a daemon).
๐ Going deeper: a thread cannot return a value directly. Store results in a list slot per thread (
results[index] = ...), or useconcurrent.futures(section 6), which gives you return values for free.
Read more: the official threading documentation.
Done here? The practice set for Part 13 โ 8 exercises with solutions โ is on the part page.