Start and Join Worker Threads
Core idea
A thread runs a callable in the same process as its creator. Thread(target=fn, args=(x,)) prepares it; start() schedules the callable and join() waits for termination. The thread does not return its target result to join. Use a queue or Future for results and errors.
from threading import Threaddef label(code): print('parcel', code)t = Thread(target=label, args=(7,))t.start()t.join()print('done')Join ensures the worker finishes before the last print.
Expected output:
parcel 7doneCheck a completed thread
from threading import Threadt = Thread(target=lambda: None)print(t.is_alive())t.start()t.join()print(t.is_alive())Before start and after join, the thread is not alive.
Expected output:
FalseFalseCommon mistake
Pass target=fn, not target=fn(). A Thread cannot be started twice. Daemon threads can stop abruptly at interpreter shutdown; prefer explicit completion for important work.
Practice
Start two workers that each produce a distinct label. Join both before reading the results; do not assert a particular worker completion order.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Thread lifecycle
Check your understanding of thread lifecycle.
What is printed?
from threading import Threadt=Thread(target=lambda:None)t.start(); t.join()print(t.is_alive())What is printed?
from threading import Threadt=Thread(target=lambda:None)t.start()print(t.join())Which action schedules the target?
What is the risk of relying on daemon shutdown?