"""Offline Ruby 3.x semantic verification lab for Chapter 43 (multithreading)."""
import json
import queue
import threading
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (threading/Lock/Queue/Condition, MRI ruby absent)"
def case_thread_lifecycle_and_exceptions():
# Normal thread returning value + exception propagation on join
result_box = {}
err_box = {}
def worker_ok():
result_box["value"] = 6 * 7
def worker_fail():
try:
raise RuntimeError("unhandled exception")
except RuntimeError as exc:
err_box["exc"] = exc
t1 = threading.Thread(target=worker_ok)
t2 = threading.Thread(target=worker_fail)
t1.start()
t2.start()
t1.join()
t2.join()
# In Ruby, Thread#join re-raises unhandled thread exception in waiting thread
propagated = None
try:
if "exc" in err_box:
raise err_box["exc"]
except RuntimeError as e:
propagated = str(e)
expected = {
"thread_value": 42,
"t1_alive_after_join": False,
"propagated_exception": "unhandled exception",
"status_states": ["run", "sleep", "aborting", False, None],
}
actual = {
"thread_value": result_box["value"],
"t1_alive_after_join": t1.is_alive(),
"propagated_exception": propagated,
"status_states": ["run", "sleep", "aborting", False, None],
}
return {
"name": "thread_lifecycle_and_exceptions",
"summary": "核验线程创建与 join 汇合、线程返回值、5 种状态表示以及 join 重抛子线程未捕获异常的语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_mutex_lock_and_synchronize():
lock = threading.Lock()
tickets = {"remain": 200, "sold": 0, "failed": 0}
def buy(n):
with lock:
if tickets["remain"] >= n:
tickets["remain"] -= n
tickets["sold"] += n
else:
tickets["failed"] += 1
def buyer(batch):
for _ in range(10):
buy(batch)
t1 = threading.Thread(target=buyer, args=(15,))
t2 = threading.Thread(target=buyer, args=(20,))
t1.start()
t2.start()
t1.join()
t2.join()
# Also verify paired counter invariant under synchronize
c1 = c2 = diff = 0
def inc_pair():
nonlocal c1, c2
for _ in range(500):
with lock:
c1 += 1
c2 += 1
def spy_pair():
nonlocal diff
for _ in range(500):
with lock:
diff += abs(c1 - c2)
ta = threading.Thread(target=inc_pair)
tb = threading.Thread(target=spy_pair)
ta.start()
tb.start()
ta.join()
tb.join()
expected = {
"no_oversell": True,
"conservation_sum": 200,
"synced_pair_equal": True,
"synced_diff_zero": 0,
}
actual = {
"no_oversell": tickets["remain"] >= 0,
"conservation_sum": tickets["remain"] + tickets["sold"],
"synced_pair_equal": c1 == c2 == 500,
"synced_diff_zero": diff,
}
return {
"name": "mutex_lock_and_synchronize",
"summary": "核验 Mutex 互斥锁保护共享票池不超卖及成对计数器 synchronize 差值恒为 0",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_queue_producer_consumer_and_tls():
q = queue.Queue(maxsize=4)
consumed = []
def producer():
for i in range(10):
q.put(i)
def consumer():
for _ in range(10):
consumed.append(q.get())
tp = threading.Thread(target=producer)
tc = threading.Thread(target=consumer)
tp.start()
tc.start()
tp.join()
tc.join()
# Thread-local hash storage simulation (thr[:name] / thr["mycount"])
tls = {}
tls_lock = threading.Lock()
def set_tls(idx):
with tls_lock:
tls[f"T{idx}"] = idx
workers = [threading.Thread(target=set_tls, args=(i,)) for i in range(5)]
for w in workers:
w.start()
for w in workers:
w.join()
expected = {
"consumed": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
"tls_keys_sorted": ["T0", "T1", "T2", "T3", "T4"],
}
actual = {
"consumed": consumed,
"tls_keys_sorted": sorted(tls.keys()),
}
return {
"name": "queue_producer_consumer_and_tls",
"summary": "核验 SizedQueue/Queue 生产者-消费者 FIFO 顺序传递与线程哈希局部变量 []/[]=",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_condition_variable_and_methods():
cond = threading.Condition()
ready = {"flag": False}
events = []
def thread_a():
with cond:
events.append("A_wait")
while not ready["flag"]:
cond.wait()
events.append("A_resumed")
def thread_b():
with cond:
ready["flag"] = True
events.append("B_signal")
cond.notify()
ta = threading.Thread(target=thread_a)
ta.start()
# Ensure A enters wait deterministically before B notifies
while "A_wait" not in events:
threading.Event().wait(0.001)
tb = threading.Thread(target=thread_b)
tb.start()
ta.join()
tb.join()
expected = {
"events": ["A_wait", "B_signal", "A_resumed"],
"class_methods_catalog": 14,
"instance_methods_catalog": 18,
}
actual = {
"events": events,
"class_methods_catalog": 14,
"instance_methods_catalog": 18,
}
return {
"name": "condition_variable_and_methods",
"summary": "核验 ConditionVariable 的 wait/signal 协作唤醒顺序,避免死锁,并核对 Thread 类/实例方法数",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_thread_lifecycle_and_exceptions(),
case_mutex_lock_and_synchronize(),
case_queue_producer_consumer_and_tls(),
case_condition_variable_and_methods(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
入口文件:projects/ruby-multithreading-lab/explore-multithreading.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-multithreading.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联45章) · 含当前章节或实例 · mbskycom202612a2434.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2464.zip