Python threading:启动、协调与收尾线程
用共享计数、消息队列和有界工作线程练习可复现的协作。
学完这一章,你能够
- 用共享计数、消息队列和有界工作线程练习可复现的协作。
线程、进程与启动方式
进程有自己的地址空间,同一进程内的线程可读写共享对象。某个线程阻塞等待 I/O 时,其他线程可以继续处理任务。本站用本机套接字实测等待收包与另一个线程执行能交错进行。
常规 CPython 3.12 的全局解释器锁限制普通 Python 字节码的线程并行。纯 Python 计算可评估进程池,I/O 等待可用线程。部分原生扩展会释放 GIL。Python 3.13 起还有可选自由线程构建,具体行为按实际构建与扩展判断。 本站让串行、两个线程和两个进程运行同一组纯 Python 整数计算,三种方式都得到了相同的结果。本机常规 CPython 3.12 中,两线程的耗时与串行接近,预热后的两进程用时更短。计时包含任务分发,进程启动和关闭在计时范围之外。任务较小或进程间传输较多时,要把这些成本算进去。解压本章 ZIP 后运行 python threading-lab/threading_cpu.py,可查看各次耗时和实际使用的线程、进程数量。
创建 Thread(target=函数, args=(值,), kwargs={...}),将函数本身交给 target。args 可传列表或元组,单元素元组需要逗号,例如 (7,),列表则写 [7]。kwargs 用字典传关键字参数。本站在 CPython 3.12 和 3.13 中分别传入 [7] 和 (7,),两次都将位置参数 7 和关键字参数 label 交给目标函数。也可继承 Thread 并覆盖 run。start 启动新线程并调用 run,直接调用 run 则在调用者线程同步执行。
join 等待目标线程退出,正常结束或超时都返回 None。超时后可用 is_alive 查看线程是否还在运行,再用 join 等待。启动前调用 join、线程等待自身以及重复 start 都会抛出 RuntimeError。name 用来标记线程,ident 启动前为 None,退出后仍可从 Thread 对象读取,标识可被后续线程复用。daemon 默认为创建者的值,也可在 start 前明确指定。只剩守护线程时进程可退出,需要可靠清理的任务应通过信号通知停止,再用 join 等待。解压本章 ZIP 后运行 python threading-lab/threading_lifecycle.py 可核对这些生命周期行为。
用锁和并发上限保护共享状态
读、改、写是一组操作。实验用屏障让两个线程读到同一个旧值,再写回,稳定复现丢失更新。给整个更新加 Lock 后可得到完整计数。with 会自动释放锁,临界区尽量短,多个锁保持一致的获取顺序。
Lock 是原始互斥锁,CPython 3.12 的 threading.Lock 是工厂,3.13 起公开为类。RLock 允许拥有锁的线程重复获取,需成对释放。locked 是 3.12 原始 Lock 的查询接口,RLock 从 3.14 才提供同名查询。 本站在 Windows CPython 3.12.14 和 3.13.12 上实测:isinstance(lock, threading.Lock) 分别抛出 TypeError 和返回 True。另一个线程可以释放已经上锁的 Lock,释放当前线程持有的 RLock 则会抛出 RuntimeError。拥有者连续获取两次 RLock 后,另一线程在释放两次之前的非阻塞尝试均返回 False,释放两次后返回 True。locked() 只查询调用当时的状态,要尝试取得锁可直接检查 acquire(blocking=False) 的结果。解压本章 ZIP 后,用要核对的解释器运行 python threading-lab/threading_versions.py。
Semaphore 管理可用配额。初值为 2 时,第三次获取必须等待或失败。BoundedSemaphore 还会拒绝使计数超过初值的释放。threading.local 的属性分别存于每个线程。 配额耗尽后,非阻塞获取和零超时获取都返回 False。普通 Semaphore 的 release(3) 增加三份配额,即使超过初值也会成功。有界信号量超额释放抛出 ValueError,原有配额保持不变。local 对象的普通属性按线程保存,子类定义的 __slots__ 槽会跨线程共享。解压本章 ZIP 后运行 python threading-lab/threading_primitives.py 可观察这些行为。
用事件、定时器和条件变量协作
Event 初始为假。set 唤醒等待者并保持真,clear 恢复假。wait(timeout) 可区分已收到信号与超时。Timer 是延后执行的线程,执行开始之前可以 cancel,需 join 核对已退出,间隔也可能因调度而延长。 本站用事件确认回调已开始,再调用 cancel()。回调仍收到位置参数 invoice 和关键字参数 token=42,并在收到放行信号后正常结束。
Condition 与锁配合。wait 在等待时释放关联锁,返回前重新取得锁。notify 与 notify_all 要在持有锁时调用,调用本身不会释放锁。使用 while 检查共享状态,醒来后重新判断谓词。 也可在持锁时调用 wait_for(谓词, timeout),它会在锁内重新求值并返回最后一次谓词结果。本站先在待办为空时发通知,谓词仍为假,消费者继续等待。放入票号 A17 再通知后,消费者得到该票号。关联的 RLock 即使被同一线程嵌套获取,等待也会暂时完全释放它,并在返回时恢复原有获取层数。实测三个等待者中先有两个响应 notify(2),随后第三个响应 notify_all(),程序应继续以共享状态为判断依据。解压本章 ZIP 后运行 python threading-lab/threading_condition.py 可查看这些结果。
条件队列的生产者在容量达到上限时等待,消费者在空队列时等待。实验使用固定清单和有限容量,检查每项按顺序交付并等待生产者和消费者退出。
用队列传递任务并等待完成
queue.Queue 可在线程间传递数据。empty 只反映观察瞬间,检查后到 get 之间可能已被另一线程取走。实验先让两个线程都观察到非空,再检验只有一个能取到项目。
每个工作线程循环执行阻塞 get,处理后在 finally 调用 task_done。生产结束时给每个消费者放一个停止标记。Queue.join 等待全部投递得到 task_done,Thread.join 分别等待工作线程退出。 处理失败时记录任务编号和错误,并在 finally 确认该项已处理。本站投入四个转换任务,其中一个触发 ValueError,另三个仍得到结果。两个消费者各收到一个停止标记,队列完成计数归零。多调用一次 task_done() 会抛出 ValueError。解压本章 ZIP 后运行 python threading-lab/threading_coordination.py 可重现事件与队列实验。
任务多时可用 ThreadPoolExecutor 限制工作线程数并获取结果。active_count 与 enumerate 可观察活动线程,current_thread 返回调用者对象,main_thread 返回主线程对象。用合理上限控制资源。 本站将两个工作线程留在同一个等待点,这时 active_count() 的值与 enumerate() 列表长度一致,列表可见主线程和两个工作线程。尚未启动的对象未出现在列表中。工作线程内 get_ident() 与当前线程对象的 ident 相同。线程数会随启动、退出而改变,这些查询适合观察状态。max_workers=2 时,第三个任务仍在排队,可以取消。另一个任务抛出的异常可通过 Future.result() 取回。解压本章 ZIP 后运行 python threading-lab/threading_inventory.py 可观察这些结果。
下载实验并完成本站自测
解压运行 python python-treading.py。用本地阅读页中的入口打开四道互动题,先作答再核对。离线解压后也可直接打开 threading-lab/quiz.html。
下载本章实验包 (mbskycom202611a463.zip) ↓ 查看运行说明 ↗
尝试一下 ↗ 在独立页面修改并运行
核心类
| 类、参数或方法 | 作用和条件 |
| threading.Thread | 构造线程,支持函数目标、参数和子类。 |
| threading.Lock | 构造互斥原始锁。 |
| threading.RLock | 同一个线程可重入,获得几次就释放几次。 |
| threading.Event | 共享标志,可通知等待的线程。 |
| threading.Condition | 配合关联锁等待共享状态改变。 |
| threading.Semaphore | 用计数限制同时持有配额的数量。 |
| threading.BoundedSemaphore | 计数超过初始值时拒绝释放。 |
| threading.Timer | 启动后在指定间隔后调用函数,开始前可取消。 |
| threading.local | 属性值在各线程间独立。 |
Thread 方法与属性
| 类、参数或方法 | 作用和条件 |
| Thread.start() | 启动新线程,每个实例只允许调用一次。 |
| Thread.run() | 线程执行入口,可覆盖。直接调用会留在调用者线程。 |
| Thread.join(timeout=None) | 等待线程结束或超时,通过 is_alive 判断超时后状态。 |
| Thread.is_alive() | 报告线程从启动到退出之间的活动状态。 |
| Thread.name | 可读写的名称,用于识别和诊断。 |
| Thread.daemon | 启动前设置,只有守护线程剩余时进程可退出。 |
| Thread.ident | 启动前通常为 None,结束后仍可读取已分配值。 |
互斥锁
| 类、参数或方法 | 作用和条件 |
| Lock.acquire(blocking=True, timeout=-1) | 可阻塞、限时或立即尝试,返回是否获得。 |
| Lock.release() / RLock.release() | 释放持有状态。RLock 需由拥有者按获取次数释放。 |
| Lock.locked() | CPython 3.12 可查询原始 Lock。RLock 的同名方法从 3.14 起提供。 |
事件
| 类、参数或方法 | 作用和条件 |
| Event.set() | 设为真,放行等待者。 |
| Event.clear() | 将标志重置为假。 |
| Event.wait(timeout=None) | 等待标志为真或到达超时,返回布尔值。 |
| Event.is_set() | 返回当前标志状态。 |
条件变量
| 类、参数或方法 | 作用和条件 |
| Condition.wait(timeout=None) | 释放锁并等待,返回前重新获取锁。 |
| Condition.notify(n=1) | 持锁通知等待者,当前仍持锁。代码须重新检查条件。 |
| Condition.notify_all() | 持锁通知全部等待者,释放锁后它们才能陆续继续。 |
模块查询
| 类、参数或方法 | 作用和条件 |
| threading.active_count() | 返回活动 Thread 对象数量,与 enumerate 的长度对应。 |
| threading.current_thread() | 返回调用者线程对象。 |
| threading.enumerate() | 列出活动 Thread 对象。 |
| threading.main_thread() | 返回解释器主线程对象。 |
| threading.get_ident() | 返回调用者标识,后续线程可能复用。 |
本章自编源码与运行范围
展开查看收起
"""Run bounded, coordinated threading examples without external services."""
from collections import deque
from concurrent.futures import ThreadPoolExecutor
import json
from queue import Empty, Queue
import socket
import subprocess
import sys
import threading as th
TIMEOUT = 5
def await_signal(event):
if not event.wait(TIMEOUT):
raise RuntimeError("Timed out while waiting for the coordination signal")
def finish(thread):
thread.join(TIMEOUT)
if thread.is_alive():
raise RuntimeError(f"{thread.name} did not exit")
def main():
checks = []
def check(name, actual, expected, inputs, operation):
if actual != expected:
raise AssertionError((name, actual, expected))
checks.append(dict(name=name,inputs=inputs,operation=operation,actual=actual,expected=expected,passed=True))
seen = []
class Reader(th.Thread):
def run(self):
seen.append(th.current_thread() is self)
probe = Reader()
probe.run()
check('direct run stays on caller', seen[:], [False], 'Reader.run()', 'Call overridden run directly')
probe.start()
finish(probe)
check('start calls run on a different thread', seen, [False, True], 'same Reader instance',
'Start once and join, then compare the thread objects')
try:
probe.start()
except RuntimeError:
check('start cannot be called twice', True, True, 'already used Thread', 'Try a second start')
else:
raise AssertionError('Thread was started twice')
names = []
for idx in range(3):
target = th.Thread(target=lambda number, *, suffix: names.append((number, suffix)),
args=(idx,), kwargs={'suffix': 'ok'})
target.start()
finish(target)
check('target receives positional and keyword arguments', names, [(0,'ok'),(1,'ok'),(2,'ok')],
[0,1,2], 'Pass a one-element tuple and keyword mapping to three actual threads')
release = th.Event()
entered = th.Event()
metadata = Queue()
def inspect():
current = th.current_thread()
alive = th.enumerate()
metadata.put([current.name,current in alive,th.main_thread() is not current,
current.ident == th.get_ident(),th.active_count() == len(alive)])
entered.set()
await_signal(release)
worker = th.Thread(target=inspect, name='stage-probe')
worker.name = 'stock-probe'
ident_before = worker.ident
worker.start()
try:
await_signal(entered)
outcome = worker.join(.01)
alive_after_timeout = worker.is_alive()
finally:
release.set()
finish(worker)
check('join timeout leaves thread alive', [outcome,alive_after_timeout,worker.is_alive()],
[None,True,False], 'worker held by Event', 'Join with timeout, signal then join again')
check('thread metadata and module inspection', [ident_before,worker.ident is not None,metadata.get_nowait()],
[None,True,['stock-probe',True,True,True,True]], 'Thread named stock-probe',
'Inspect module-level functions from within the worker and the id before and after')
child_code = (
'from threading import Event, Thread\n'
'entered=Event(); blocked=Event()\n'
'def worker():\n entered.set(); blocked.wait()\n'
'Thread(target=worker,daemon=True).start()\n'
'if not entered.wait(2): raise RuntimeError("not started")\n'
'print("worker reached wait",flush=True)\n'
)
child = subprocess.run([sys.executable,'-I','-B','-c',child_code],capture_output=True,
text=True,timeout=TIMEOUT,check=True)
check('daemon process can exit without blocked worker', child.stdout.strip(),'worker reached wait',
'isolated subprocess with a blocked daemon', 'Wait for actual worker signal, then observe process exit')
lock = th.Lock()
held_before = lock.locked()
with lock:
attempts = Queue()
tester = th.Thread(target=lambda: attempts.put([lock.acquire(False),lock.acquire(timeout=.01)]))
tester.start()
finish(tester)
held_during = lock.locked()
reacquired = lock.acquire(False)
lock.release()
check('lock acquisition contention and release', [attempts.get_nowait(),reacquired],[ [False,False],True],
'main owns Lock, another thread tries immediate and bounded acquisition',
'Try both acquisitions while held and acquire again after release')
check('Lock state and 3.12 RLock API', [held_before,held_during,lock.locked(),
hasattr(th.RLock(),'locked')],
[False,True,False,sys.version_info >= (3,14)], 'primitive Lock and RLock',
'Query lock state and inspect version-dependent RLock API')
recursive = th.RLock()
def contender():
output = Queue()
def attempt():
obtained = recursive.acquire(False)
output.put(obtained)
if obtained:
recursive.release()
t = th.Thread(target=attempt)
t.start()
finish(t)
return output.get_nowait()
recursive.acquire()
recursive.acquire()
twice = contender()
recursive.release()
once = contender()
recursive.release()
check('RLock releases only after both acquisitions',[twice,once,contender()],[False,False,True],
'two acquisitions from one owner', 'Attempt to enter from a second thread after each release')
barrier = th.Barrier(2, timeout=TIMEOUT)
count = 0
def lose_update():
nonlocal count
snapshot = count
barrier.wait()
count = snapshot + 1
threads = [th.Thread(target=lose_update) for _ in range(2)]
for t in threads:
t.start()
for t in threads:
finish(t)
check('shared read modify write loses an update',count,1,'two writers with a barrier after reading',
'Force both writers to read before either can store the increment')
count = 0
def increment():
nonlocal count
with lock:
count += 1
threads = [th.Thread(target=increment) for _ in range(10)]
for t in threads:
t.start()
for t in threads:
finish(t)
check('locked increments retain every update',count,10,'ten threads using one Lock',
'Increment inside a critical section and wait for all threads')
semaphore = th.Semaphore(2)
initial = [semaphore.acquire(False) for _ in range(3)]
semaphore.release()
after_release = semaphore.acquire(False)
semaphore.release(2)
check('Semaphore limits acquisitions',[initial,after_release],[[True,True,False],True],
'Semaphore(2)', 'Try a third acquisition before releasing a slot')
bounded = th.BoundedSemaphore(1)
bounded.acquire()
bounded.release()
try:
bounded.release()
except ValueError:
check('BoundedSemaphore rejects over-release',True,True,'BoundedSemaphore(1) already at capacity',
'Attempt a release beyond its initial value')
else:
raise AssertionError('Expected ValueError for over-release')
local = th.local()
local.tag = 'main'
values = Queue()
def local_values():
before = getattr(local,'tag',None)
local.tag = 'worker'
values.put((before,local.tag))
t = th.Thread(target=local_values)
t.start()
finish(t)
check('thread local attributes are isolated',[local.tag,values.get_nowait()],['main',(None,'worker')],
'one threading.local object', 'Assign a worker attribute and compare it to the main-thread attribute')
signal = th.Event()
begun = th.Event()
wait_results = Queue()
def wait():
begun.set()
wait_results.put(signal.wait(TIMEOUT))
t = th.Thread(target=wait)
t.start()
await_signal(begun)
before_set = signal.is_set()
timed_out = signal.wait(.01)
signal.set()
finish(t)
was_set = signal.is_set()
signal.clear()
check('Event flag timeout wake and clear',[before_set,timed_out,wait_results.get_nowait(),was_set,signal.is_set()],
[False,False,True,True,False],'Event initially unset with one actual worker',
'Test timeout, set the flag, join the worker and clear the flag')
timer_signal = th.Event()
elapsed_timer = th.Timer(.01,timer_signal.set)
elapsed_timer.start()
await_signal(timer_signal)
finish(elapsed_timer)
never = th.Event()
cancelled = th.Timer(60,never.set)
cancelled.start()
cancelled.cancel()
finish(cancelled)
check('Timer runs and cancelled Timer stays silent',[timer_signal.is_set(),never.is_set()],[True,False],
'a short Timer and a separately cancelled Timer','Observe the first callback and cancel the second before execution')
cond = th.Condition()
waiting = Queue()
awakened = Queue()
permits = 0
def condition_waiter(number):
nonlocal permits
with cond:
waiting.put(number)
end = cond.wait_for(lambda: permits > 0, timeout=TIMEOUT)
if not end:
return
permits -= 1
awakened.put(number)
waiters = [th.Thread(target=condition_waiter,args=(i,)) for i in range(3)]
for t in waiters:
t.start()
ready = sorted(waiting.get(timeout=TIMEOUT) for _ in waiters)
with cond:
permits = 1
cond.notify(1)
held_after_notify = awakened.empty()
first = awakened.get(timeout=TIMEOUT)
with cond:
permits = 2
cond.notify_all()
for t in waiters:
finish(t)
wake_order = sorted([first,awakened.get_nowait(),awakened.get_nowait()])
with cond:
timed_out = cond.wait(.01)
check('Condition notification reacquires lock',[held_after_notify,timed_out],[True,False],
'waiters use one condition lock','Notify while locked and confirm no worker proceeds until lock release')
check('Condition notify one and then all',[ready,wake_order,permits],[[0,1,2],[0,1,2],0],
'three waiting workers and one then two permits','Wait for one completion, then release all remaining waiters')
handoff = th.Condition()
work = deque()
expected = [4,1,9,6,3,8]
received = []
lengths = []
def producer():
for item in expected:
with handoff:
while len(work) == 2:
if not handoff.wait(TIMEOUT):
raise RuntimeError('producer timeout')
work.append(item)
lengths.append(len(work))
handoff.notify_all()
def consumer():
for _ in expected:
with handoff:
while not work:
if not handoff.wait(TIMEOUT):
raise RuntimeError('consumer timeout')
received.append(work.popleft())
handoff.notify_all()
workers = [th.Thread(target=producer),th.Thread(target=consumer)]
for t in workers:
t.start()
for t in workers:
finish(t)
check('Condition coordinates bounded producer and consumer',[received,len(work),max(lengths)<=2],
[expected,0,True],'six fixed values, capacity two',
'Exchange values using condition predicates and check bounds and order')
q = Queue()
q.put('one')
simultaneous = th.Barrier(2,timeout=TIMEOUT)
readiness = Queue()
results = Queue()
def check_then_get():
readiness.put(not q.empty())
simultaneous.wait()
try:
results.put(q.get_nowait())
except Empty:
results.put('empty')
else:
q.task_done()
workers = [th.Thread(target=check_then_get) for _ in range(2)]
for t in workers:
t.start()
for t in workers:
finish(t)
check('Queue empty check is not an atomic reservation',
[[readiness.get_nowait() for _ in workers],sorted(results.get_nowait() for _ in workers)],
[[True,True],['empty','one']], 'one item and two consumers synchronized after empty check',
'Allow both to observe nonempty, then let both attempt to take the item')
stop = object()
deliveries = Queue()
def queue_worker():
while True:
item = q.get(timeout=TIMEOUT)
try:
if item is stop:
return
deliveries.put(item * 2)
finally:
q.task_done()
workers = [th.Thread(target=queue_worker) for _ in range(2)]
for item in (5,3,7,stop,stop):
q.put(item)
for t in workers:
t.start()
for t in workers:
finish(t)
q.join()
check('Queue sentinel and task accounting',sorted(deliveries.get_nowait() for _ in range(3)),[6,10,14],
'three items and one stop token per worker','Account for every item, join workers and wait for the queue')
with ThreadPoolExecutor(max_workers=2) as pool:
output = list(pool.map(abs,[-4,1,-6]))
check('ThreadPoolExecutor returns mapped results',output,[4,1,6],[-4,1,-6],
'Submit work to a bounded executor and collect the ordered results')
recv_ready = th.Event()
background_done = th.Event()
payload = Queue()
receiver, sender = socket.socketpair()
with receiver, sender:
receiver.settimeout(TIMEOUT)
def receive():
recv_ready.set()
payload.put(receiver.recv(1).decode('ascii'))
waiting = th.Thread(target=receive)
independent = th.Thread(target=background_done.set)
waiting.start()
await_signal(recv_ready)
independent.start()
await_signal(background_done)
before_send = payload.empty()
sender.sendall(b'X')
finish(independent)
finish(waiting)
check('independent thread runs before socket data arrives',[before_send,payload.get_nowait()],[True,'X'],
'local connected sockets and a second worker','Block receiving until after another worker reports progress')
print(json.dumps(checks,ensure_ascii=False))
if __name__ == '__main__':
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。
本章附件与实例包
常见错误与边界检查
- 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。
技术规范与官方资料
练习与参考解答
查看参考解答
比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。