"""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()
本例需在 Windows CPython 3.12, real bounded threads, loopback socket pair, and isolated daemon shutdown 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPython 3.12, real bounded threads, loopback socket pair, and isolated daemon shutdown
入口文件:projects/python-lab/python-treading.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python-treading.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPython 3.12, real bounded threads, loopback socket pair, and isolated daemon shutdown。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a302.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip