蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行离线 Python 校验:Rust 线程 spawn/join、move 所有权转移、mpsc 通道与互斥锁

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-concurrency.py
explore-concurrency.py159 行
"""Offline Rust semantic verifier for Chapter 26: Concurrency (spawn/join, move ownership, mpsc channel, Mutex)."""
import json
import queue
import threading


class OwnershipMoveError(Exception):
    pass


class OwnedBox:
    """Models a non-Copy owned String whose ownership moves across threads or channels."""

    def __init__(self, value: str) -> None:
        self._value: str | None = value

    def move_out(self) -> str:
        if self._value is None:
            raise OwnershipMoveError("use of moved value")
        val = self._value
        self._value = None
        return val

    @property
    def is_moved(self) -> bool:
        return self._value is None


def run_cases() -> list[dict]:
    cases = []

    # Case 1: thread::spawn + join() completes all 5 child steps and 3 main steps
    child_steps: list[int] = []
    main_steps: list[int] = []

    def worker() -> None:
        for i in range(5):
            child_steps.append(i)

    t = threading.Thread(target=worker)
    t.start()
    for i in range(3):
        main_steps.append(i)
    t.join()

    # Also verify closure syntax & type inference (`|num: i32| -> i32 { num + 1 }` and `|num| num + 1`)
    inc_typed = lambda num: num + 1
    actual_1 = {
        "main_steps": main_steps,
        "child_steps_after_join": child_steps,
        "closure_inc_5": inc_typed(5),
    }
    expected_1 = {
        "main_steps": [0, 1, 2],
        "child_steps_after_join": [0, 1, 2, 3, 4],
        "closure_inc_5": 6,
    }
    cases.append(dict(
        name="thread_spawn_closure_and_join",
        summary="Verify spawned thread completes all 5 steps when joined and closure inc(5) == 6",
        expected=expected_1,
        actual=actual_1,
        passed=actual_1 == expected_1,
    ))

    # Case 2: move closure ownership transfer into spawned thread
    owned_s = OwnedBox("hello")
    moved_val = owned_s.move_out()
    captured: list[str] = []

    def moved_worker(val: str) -> None:
        captured.append(val)

    t2 = threading.Thread(target=moved_worker, args=(moved_val,))
    t2.start()
    t2.join()

    use_after_move_blocked = False
    try:
        owned_s.move_out()
    except OwnershipMoveError:
        use_after_move_blocked = True

    actual_2 = {
        "thread_received": captured[0],
        "parent_binding_moved": owned_s.is_moved,
        "use_after_move_blocked": use_after_move_blocked,
    }
    expected_2 = {
        "thread_received": "hello",
        "parent_binding_moved": True,
        "use_after_move_blocked": True,
    }
    cases.append(dict(
        name="move_closure_ownership_transfer",
        summary="Verify move closure transfers owned value into child thread and blocks parent reuse",
        expected=expected_2,
        actual=actual_2,
        passed=actual_2 == expected_2,
    ))

    # Case 3: std::sync::mpsc::channel message passing + Mutex shared counter determinism
    ch: queue.Queue[str] = queue.Queue()
    msg_box = OwnedBox("hi")

    def sender(val: str) -> None:
        ch.put(val)

    t3 = threading.Thread(target=sender, args=(msg_box.move_out(),))
    t3.start()
    received = ch.get(timeout=5.0)
    t3.join()

    lock = threading.Lock()
    counter = [0]

    def bump() -> None:
        for _ in range(50):
            with lock:
                counter[0] += 1

    workers = [threading.Thread(target=bump) for _ in range(4)]
    for w in workers:
        w.start()
    for w in workers:
        w.join()

    actual_3 = {
        "mpsc_received": f"Got: {received}",
        "sender_val_moved": msg_box.is_moved,
        "mutex_counter_total": counter[0],
    }
    expected_3 = {
        "mpsc_received": "Got: hi",
        "sender_val_moved": True,
        "mutex_counter_total": 200,
    }
    cases.append(dict(
        name="mpsc_channel_and_mutex_sync",
        summary="Verify mpsc tx.send/rx.recv message delivery and 4-thread Mutex counter == 200",
        expected=expected_3,
        actual=actual_3,
        passed=actual_3 == expected_3,
    ))

    return cases


def main() -> None:
    payload = {
        "version": "CPython 3.12.14 offline Rust semantic verifier (rustc absent)",
        "cases": run_cases(),
    }
    print(json.dumps(payload, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/rust-concurrency-lab/explore-concurrency.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-concurrency.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Rust

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip

下载课程关联工程包:Rust

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1199.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习