Rust 学习笔记 21:并发编程 (无畏并发)

Rust 学习笔记 21:并发编程 (无畏并发) “Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once.” – Rob Pike 在很多语言中,并发编程是噩梦。数据竞争 (Data Race)、死锁 (Deadlock)、竞态条件 (Race Condition) 让人防不胜防。 Rust 号称 “Fearless Concurrency”(无畏并发)。它利用所有权和类型系统,在编译期就把数据竞争扼杀在摇篮里。 1. 使用线程 Rust 默认使用 1:1 线程模型,即一个 Rust 线程对应一个操作系统线程。 1use std::thread; 2use std::time::Duration; 3 4fn main() { 5 thread::spawn(|| { 6 for i in 1..10 { 7 println!("hi number {} from the spawned thread!", i); 8 thread::sleep(Duration::from_millis(1)); 9 } 10 }); 11 12 for i in 1..5 { 13 println!("hi number {} from the main thread!", i); 14 thread::sleep(Duration::from_millis(1)); 15 } 16} 注意:当主线程结束时,所有派生线程都会被强制终止,无论它们是否执行完。 ...

2025-11-29 · 2 min · 221 words · 老墨

Rust 学习笔记 05:所有权 (Ownership) 上

Rust 学习笔记 05:所有权 (Ownership) 上 “I thought I knew what ownership meant until I met the borrow checker.” – Anonymous Rustacean 终于来到了 Rust 的核心 —— 所有权 (Ownership)。 作为 Go 开发者,我们习惯了 GC(垃圾回收)帮我们打理一切。我们随手创建一个指针,传给函数,传给 Channel,从来不需要关心它什么时候被释放。因为有 GC 在兜底。 但在 Rust 里,没有 GC。但它也没有让我们像 C++ 那样手动 malloc/free。 那它是怎么管理内存的? 答案就是:所有权系统 + 编译器静态检查。 1. 核心原则 所有权规则非常霸道,但只有三条: Rust 中的每一个值都有一个被称为其 所有者 (owner) 的变量。 值在任一时刻有且只有一个所有者。 当所有者(变量)离开作用域,这个值将被丢弃 (Drop),内存被释放。 这听起来很像作用域管理,但最关键的是第二条:有且只有一个所有者。 2. 移动 (Move) 语义 在 Go 中,变量赋值默认是值拷贝(对于指针是拷贝地址)。 1// Go 代码 2s1 := "hello" 3s2 := s1 4// 现在 s1 和 s2 都指向同一个字符串,随便用 但在 Rust 中,对于复杂类型(如 String,在堆上分配),情况完全不同: ...

2024-07-20 · 2 min · 274 words · 老墨