Threading Basics
The threading module provides the Thread class and the synchronization primitives that go with it. A thread runs the function you give it in parallel with the main thread of your program, sharing the same memory space. This chapter covers the Thread lifecycle; later chapters add locks, queues, and pools on top of it.
The Thread Class
The constructor takes a target (the callable), optional args/kwargs, and a name. The important lifecycle methods are:
start()- schedules the thread to run its target. Calling it twice raisesRuntimeError.is_alive()- true while the target is executing.join(timeout)- blocks until the thread finishes (or the timeout expires).daemon- daemon threads do not keep the interpreter alive; they are killed when only daemon threads remain.
Minimal Example
import threading
def greet(who):
print(f"hello from {who}")
t = threading.Thread(target=greet, args=("worker-1",), name="greeting")
t.start()
t.join() # wait for it before exiting
print("main thread done")
Subclassing Thread
Alternatively, subclass Thread and override run(). This style keeps per-thread state as attributes and is handy when the thread has real identity in your application:
import threading
import time
class Reporter(threading.Thread):
def __init__(self, interval):
super().__init__(daemon=True)
self.interval = interval
def run(self):
while True:
print("still working...")
time.sleep(self.interval)
r = Reporter(1)
r.start()
time.sleep(3) # main thread exits; daemon reporter is stopped automatically
print("exiting")
Summary
Create threads with a target function (or by subclassing), start them, and join them when the main thread needs their completion. Daemon threads are the standard pattern for background helpers that should not block program exit.