Python threading 模块

Thread objects, daemon threads, locks, events and timers.

Intermediate
Key PointsDaemon threads die with the main thread — good for background heartbeats, wrong for anything that must finish.

Thread Objects

Either pass a target or subclass and override run().

Python
import threading
import time


def job(name, n):
    for i in range(n):
        print(name, i)
        time.sleep(0.1)


t1 = threading.Thread(target=job, args=("A", 2))
t2 = threading.Thread(target=job, args=("B", 2))
t1.start(); t2.start()
t1.join(); t2.join()
print("done")
Output
A 0
B 0
A 1
B 1
done

Daemon and Timer

A daemon thread does not block process exit. Timer runs once after a delay — handy as a timeout fallback.

Python
import threading
import time

def heartbeat():
    while True:
        print("ping")
        time.sleep(1)

threading.Thread(target=heartbeat, daemon=True).start()

t = threading.Timer(1.5, lambda: print("timeout fired"))
t.start()
time.sleep(2)
print("main exits, daemon dies")
Output
ping
timeout fired
ping
main exits, daemon dies

Event for Signalling

Event is the lightest inter-thread signal: one thread calls set(), others wake from wait().

Python
import threading

ready = threading.Event()

def worker():
    print("waiting")
    ready.wait()            # 阻塞直到 set()
    print("go")

threading.Thread(target=worker).start()
ready.set()
Output
waiting
go
There is no thread kill API. Stop a thread cooperatively with an Event flag.

Friends & Partners