Rust 并发编程
核对并发与并行区分、std::thread::spawn 创建线程、闭包参数与 join 等待、move 闭包跨线程转移所有权,以及 std::sync::mpsc 通道消息传递。
学完这一章,你能够
- 核对并发与并行区分、std::thread::spawn 创建线程、闭包参数与 join 等待、move 闭包跨线程转移所有权,以及 std::sync::mpsc 通道消息传递。
并发与并行概念、线程模型与编译期安全保障
并发(Concurrent)强调程序多个部分独立推进,并行(Parallel)强调物理多核上的真正同时执行,并发程序在多核环境下往往演化为并行。线程是进程内部独立的执行流;不同于依赖重型运行时/GC 的托管语言或缺乏编译期检查的 C/C++,Rust 像 C/C++ 一样无额外运行时开销,同时凭借所有权、借用规则与 `Send`/`Sync` 特性在编译期消灭数据竞争等大量常见并发缺陷。当然,死锁或业务时序缺陷仍需开发者谨慎设计避免。
thread::spawn、闭包与 join() 等待
在 Rust 中调用 `std::thread::spawn` 启动新线程,可传入无参函数名(如 `spawn_function`)或更惯用的匿名闭包 `|| { ... }`。主线程与子线程交替执行,具体交错顺序受操作系统调度影响;若主线程提前结束,尚未打印完 5 次的子线程也会随进程退出被强制终止。闭包语法为 `|参数1, ...| -> 返回类型 { 函数体 }`,参数与返回类型在可推断时通常省略(如 `let inc = |num| { num + 1 };`,调用 `inc(5)` 返回 `6`)。
为确保子线程完整执行完毕,`thread::spawn` 会返回一个 `JoinHandle`,在主线程末尾调用 `handle.join().unwrap()` 即可阻塞等待子线程全部结束,从而保证主线程的 3 次打印与子线程的 5 次打印都能完整呈现。本站离线校验器使用真实多线程验证 `join()` 后主线程 3 步与子线程 5 步全部落盘且闭包 `inc(5) == 6`。
move 闭包所有权迁移与 mpsc 消息传递
由于操作系统线程的存活期可能超过创建它的当前栈帧,子线程闭包默认不能随意借用父作用域的局部变量(注:字符串字面量 `&'static str` 拥有 `'static` 生命周期且实现 `Copy`,但一旦换成堆分配的 `String` 或局部栈切片,不加 `move` 就会直接触发借用期编译报错)。在闭包前加上 `move` 关键字(`thread::spawn(move || { ... })`)可强制将捕获值的所有权安全移入子线程,同时阻止父线程再次误用。
Rust 倡导通过通道(Channel)实现消息传递并发:`std::sync::mpsc::channel()`(多生产者、单消费者)返回发送端 `tx` 与接收端 `rx`。子线程通过 `move` 接管 `tx` 并调用 `tx.send(String::from("hi")).unwrap()`(同时将 `val` 的所有权移交通道),主线程通过阻塞方法 `rx.recv().unwrap()` 收到消息并输出 `Got: hi`。本站离线校验器验证了 `move` 转移后父端复用被拦截、`mpsc` 跨线程收发 `Got: hi` 以及 4 线程 `Mutex` 互斥计数精确等于 `200`。
运行离线 Python 校验:Rust 线程 spawn/join、move 所有权转移、mpsc 通道与互斥锁
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为新线程可能比当前栈帧活得更久,编译器要求闭包满足 'static 约束,move 会把局部变量的所有权移进线程闭包内防止悬垂引用;tx.send(val) 同样会转移 val 的所有权到通道接收端,发送后原线程不能再访问 val。