有关于并发(concurrency)和并行(parallelism)的定义每个人可能有不一样的解释。笔者认为并行算是并发的子集合,所谓的「并发」,是指在某项工作结束之前,另一项工作就开始了,但这些工作可以是同时运行,也可以是交替运行。而所谓的「并行」,是并发的一种设计方式,能将工作交给不同的处理器(逻辑处理器)来运行,而达成同时运行两项以上工作的目的。编程语言如 JavaScript,虽然只支持单线程,但是它也可以并发处理工作,例如它能在等待 I/O 处理的同时,去运行其它的函数。编程语言如 Java,可以创建出多个线程来并发处理工作,当操作系统可以使用多个处理器(逻辑处理器)时,线程就可以被分散到各个处理器(逻辑处理器)来同时运行,且如果线程数量大于处理器(逻辑处理器)数量的话,也会交替运行;如果操作系统没有多个处理器(逻辑处理器)的话,则只会让其交替处理正在运行的线程。
编程语言如 Golang,可以利用 goroutine(go 函数)来并发处理工作,它利用多线程的方式去完成每个 goroutine 的工作,但并不是每个 goroutine 都会有一个独立的线程,线程的数量透过 GOMAXPROCS 环境变量来设置,默认值即为处理器(逻辑处理器)的数量。假设 GOMAXPROCS 为 8,而 goroutine 的数量有 100 的话,Golang 程序只会使用 8 个线程去完成这些 goroutine。
Rust 原生并没有什么特别的方式来实作并发程序(但可以使用「async / await」语法搭配第三方函数库来实作并发程序,若想更进一步了解可以参考这篇文章),也是和 Java 一样要自行创建出多个线程。虽然并发程序会让程序复杂度提升,增加潜在 Bug 出现的概率,而且也不易调试,不过,Rust 本身的拥有权规则,可以避免掉并发程序大部份常见的潜在 Bug。
使用多线程来开发程序可以增加程序的性能,因为在操作系统能使用的处理器(逻辑处理器)数量足够的情况下,被分配到不同线程的程序部份是可以被「同时」运行的。举例来说,假设完成工作 A 所需的时间是 5 秒,完成工作 B 所需的时间是 6 秒。只使用单一线程来完成工作 A 和工作 B 需要 5+6=11 秒的时间,而如果使用多线程来同时完成工作 A 和工作 B,只需要 Max(5,6)=6 秒的时间。
而多线程的程序可能会遭遇到以下几个问题:
2. 死结(Deadlock):两个线程彼此等待对方发布资源的使用权,而造成这两个线程永远无法继续运行。
3. 多线程的程序在每次运行时,程序的运行顺序不一定会相同,因此当发生 Bug 时,会很难去重现出来。
要使用 Rust 编程语言创建新的线程,可以透过标准函数库 std::thread 模块提供的 spawn 函数,搭配闭包来使用。举例来说:
use std::thread;
use std::time::Duration;
fn main() {
thread::spawn(|| {
for i in 1..10 {
println!("hi number {i} from the spawned thread!");
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("hi number {i} from the main thread!");
thread::sleep(Duration::from_millis(1));
}
}
以上程序运行结果,可能如下:
hi number 1 from the spawned thread!
hi number 2 from the main thread!
hi number 2 from the spawned thread!
hi number 3 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the main thread!
hi number 4 from the spawned thread!
std::thread 模块提供的 sleep 函数,可以让其所在的线程进入睡眠状态,让其它线程能有更多机会被运行到。新的线程内的 for 循环计数范围虽然为 1 到 10(包含 1,不包含 10),但由于主线程的 for 循环计数范围只有 1 到 5(包含 1,不包含 5),因此主线程的 for 循环很有可能会在新线程内的 for 循环结束之前就结束了,一旦主线程的程序都运行完成,即便新线程还没运行完,程序也会直接停止。因此在程序运行的输出结果中,没有看到新线程的 for 循环当 i 大于 4 时的结果是正常的。
std::thread 模块的 spawn 函数会回传 JoinHandle 结构实体,我们可以利用这个结构实体,将其对应的线程加入(join)至其他线程中来运行。可以在 JoinHandle 结构实体所对应的线程之外调用该 JoinHandle 结构实体提供的 join 方法,使其它的线程能够等待 JoinHandle 结构实体对应的线程运行完成之后再继续运行。举例来说:
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..10 {
println!("hi number {i} from the spawned thread!");
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("hi number {i} from the main thread!");
thread::sleep(Duration::from_millis(1));
}
handle.join().unwrap();
}
以上程序运行结果,可能如下:
hi number 1 from the spawned thread!
hi number 2 from the main thread!
hi number 2 from the spawned thread!
hi number 3 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the main thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!
我们让主线程在 for 循环结束运行之后,去等待新线程运行完,再结束程序,因此程序可以输出新线程中 for 循环计数范围为 1 到 10(包含 1,不包含 10)的完整结果。
先前章节中学到的「借用」,在一般情况下无法跨线程使用,举例来说:
use std::thread;
fn main() {
let a = 5;
let handle = thread::spawn(|| {
println!("{a}");
});
handle.join().unwrap();
}
以上程序会编译错误,因为主程序中的变量 a,无法借用给要在新线程运行的闭包。
然而我们可以替闭包加上 move 关键字,让闭包主体内使用其所在的 scope 的资源去尝试「拷贝」或是「移动」,而不是「借用」,程序就可以通过编译了。程序如下:
use std::thread;
fn main() {
let a = 5;
let handle = thread::spawn(move || {
println!("{a}");
});
handle.join().unwrap();
}
在很多情况下,我们还是必须要让相同的数据在不同的线程中被使用,此时可以透过「消息传递」(message passing)来达成目的。
套用 Golang 文档中的一句话:
意思为:不要使用共享内存来让线程彼此沟通,而是要用沟通的方式去分享内存中的数据。
Rust 编程语言的标准函数库,提供了 std::sync 模块,提供了一些工具来协助我们处理线程间的同步。其中的子模块 mpsc (multi-producer, single-consumer FIFO queue communication primitives),便是利用「消息传递」的方式来实作的。
我们可以先使用 mpsc 模块提供的 channel 函数替要彼此同步的线程创建出「通道」。channel 函数会回传一个元组,第一个元素为 Sender 结构实体,第二个元素为 Receiver 结构实体。透过 Sender 结构实体发送出的消息,可以被 Receiver 结构实体接收到,无论当时 Sender 结构实体或是 Receiver 结构实体被移动到哪个线程。
举例来说:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("Got: {received}");
}
以上程序,第 5 行我们创建出了一个新的通道,并在第 10 行新线程中,使用 Sender 结构实体的 send 方法将字符串 hi 送出。程序第 13 行主线程中,使用 Receiver 结构实体的 recv 方法来接收从 Sender 结构实体送出的消息,主线程运行时会先停在该 recv 方法,直到接收到来自同通道的 Sender 结构实体的消息后,才会继续运行。
程序运行结果如下:
如果不用 Receiver 结构实体的 recv 方法,而是使用其 try_recv 方法的话,主线程运行时就不会停住,会直接回传被 Result 枚举所包裹的结果。
通道所能发送的数据类型并没有限制,因此如果要传递多种数据的话,可以搭配 Vec 结构体使用。举例来说:
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
for val in vals {
tx.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
for received in rx {
println!("Got: {received}");
}
}
Receiver 结构体本身和其参考类型皆有实作 IntoIterator 特性,因此可以直接被使用在 for 循环。程序运行结果如下:
Got: from
Got: the
Got: thread
Sender 结构实体可以被拷贝,也就是说,我们可以用多个 Sender 结构实体,透过同一个通道将消息传递给同一个 Receiver 结构实体。举例来说:
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
let tx_1 = tx;
let tx_2 = tx_1.clone();
thread::spawn(move || {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
for val in vals {
tx_1.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
thread::spawn(move || {
let vals = vec![
String::from("more"),
String::from("messages"),
String::from("for"),
String::from("you"),
];
for val in vals {
tx_2.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
for received in rx {
println!("Got: {received}");
}
}
以上程序运行结果,可能如下:
Got: more
Got: from
Got: messages
Got: the
Got: for
Got: thread
Got: you
当我们的数据需要有多个拥有者时,消息传递的线程沟通方式就不太适合了,此时我们还是得回归共享内存的作法。在前面的章节中,我们学会了 Rc 结构体,可以让数据的拥有者不只限于一个,然而,Rc 结构体并不能用在多线程的场合,因为会很容易造成竞态条件的问题。
举例来说:
use std::cell::RefCell;
use std::rc::Rc;
use std::thread;
fn main() {
let a = 5;
let r = RefCell::new(a);
let b = Rc::new(r);
let mut handles = vec![];
for _ in 1..=10 {
let c = b.clone();
let handle = thread::spawn(move || {
let num = c.borrow_mut();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *b.borrow());
}
以上程序会编译失败,因为 Rc 结构体并不是「线程安全」(thread-safe)的设计,如果它可以被允许用在多个线程上,在参考的计数上将会出现问题。还好 std::sync 模块有提供一个 Atomic 版本的 Rc 结构体,称为 Arc。Arc 结构体可以被用在多线程的场合,以上程序可以使用 Arc 结构体改写如下:
use std::cell::RefCell;
use std::sync::Arc;
use std::thread;
fn main() {
let a = 5;
let r = RefCell::new(a);
let b = Arc::new(r);
let mut handles = vec![];
for _ in 1..=10 {
let c = b.clone();
let handle = thread::spawn(move || {
let num = c.borrow_mut();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *b.borrow());
}
以上程序依然会编译失败,因为 RefCell 结构体并不是「线程安全」(thread-safe)的设计,如果它可以被允许用在多个线程上,当同一个数据被多个线程同时访问时,就会发生竞态条件的问题。还好 std::sync 模块也有提供一个好用的结构体来解决这个问题,称为 Mutex。Mutex 结构体可以被用在多线程的场合,因为它会替数据创建出「互斥锁」(mutex's lock),想要拿到该笔数据的拥有者必须要先拿到数据的互斥锁才能访问该数据,且在结束数据的使用后,还要将数据的互斥锁还回去,以供之后其它的拥有者来使用。以上程序可以使用 Mutex 结构体改写如下:
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
fn main() {
let a = 5;
let m = Mutex::new(a);
let b = Arc::new(m);
let mut handles = vec![];
for _ in 1..=10 {
let c = b.clone();
let handle = thread::spawn(move || {
let mut num = c.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *b.lock().unwrap());
}
Mutex 结构实体并没有提供 borrow 或是 borrow_mut 方法,取而代之的是 lock 方法。调用 lock 方法时会进行等待,直到能取得该 Mutex 结构实体所使用的互斥锁后,才去取得互斥锁,并且将数据本身放在 MutexGuard 结构实体中,以 Result 枚举包裹并回传出来。MutexGuard 结构体也是一种智能型指针,其实体可以作为不可变参考和可变参考来使用。另外,Mutex 结构实体还有一个 try_lock 方法,即为 lock 方法的不等待版本。
以上程序会编译成功,并且输出:
正确答案!
以性能来说,有「线程安全」的 Arc 结构体和 Mutex 结构体会比 Rc 结构体和 RefCell 结构体还要差一点,因此我们在单线程的场合下要使用 Rc 结构体和 RefCell 结构体,而在多线程的场合下才去使用 Arc 结构体和 Mutex 结构体会比较好。另外,在之前的章节中有提到,Rc 结构体和 RefCell 结构体的组合可能会造成内存泄漏,如果改用 Arc 结构体和 Mutex 结构体的组合也是一样会有!而且当 Arc 结构体和 Mutex 结构体用在多线程时,还可能会导致死结的发生,举例来说:
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
fn main() {
let x = 0;
let y = 0;
let x1 = Arc::new(Mutex::new(x));
let y1 = Arc::new(Mutex::new(y));
let x2 = x1.clone();
let y2 = y1.clone();
thread::spawn(move || {
for _ in 1..=1000 {
let i = x2.lock().unwrap();
let j = y2.lock().unwrap();
let _ = *i + *j;
}
});
for _ in 1..=1000 {
let u = y1.lock().unwrap();
let v = x1.lock().unwrap();
let _ = *u + *v;
}
}
以上程序,可能会因为主线程和新的线程发生死结而导致程序永远无法运行结束。发生死结的契机为,新线程在程序第 17 行的变量 i 拿到 x 的互斥锁的同时,主线程正好已经运行完程序第 24 行,变量 u 拿到 y 的互斥锁。接着新线程在程序第 18 行想要让变量 j 拿 y 的互斥锁,就需要等主线程将互斥锁发布;而主线程此时想要让程序第 25 行的变量 v 拿 x 的互斥锁,就需要等新线程将互斥锁发布。像这种多个线程互相等待对方发布资源的情况,就是死结啦!
除了 Arc 结构体和 Mutex 结构体可能会发生死结之外,「消息传递」也是有可能会发生的。
举例来说:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx1, rx1) = mpsc::channel();
let (tx2, rx2) = mpsc::channel();
thread::spawn(move || {
println!("spawned thread is waiting for channel 1");
rx1.recv().unwrap();
println!("spawned thread is sending channel 2");
tx2.send(()).unwrap();
});
println!("main thread is waiting for channel 2");
rx2.recv().unwrap();
println!("main thread is sending channel 1");
tx1.send(()).unwrap();
}
以上程序,在新线程发送消息至第二个通道前,会先尝试接收来自第一个通道的消息;而主线程则是要在收到来自第二个通道的消息后,才会发送消息至第一个通道。因此,这两个线程彼此都在等待对方的消息,死结发生!程序运行结果如下:
spawned thread is waiting for channel 1
结论
Rust 编程语言严格的拥有权规则,使得开发并发程序的过程更有条理,更不易在运行阶段出错(尤其是竞态条件的部份)。虽然还是有些典型的多线程问题可能会发生,但已经比其它编程语言要好多了!在下一章节,我们将会学习如何在 Rust 编程语言中应用面向对象概念来开发程序。
下一章:面向对象编程。
