面试题答案
一键面试Rust线程停放基本原理
Rust中的线程停放(thread parking)是一种线程同步机制,允许线程暂停执行(停放),直到被另一个线程唤醒。这一机制基于std::thread::park
和std::thread::unpark
函数。park
函数会暂停当前线程的执行,将其从调度器中移除,直到该线程的unpark
方法被调用。unpark
函数会唤醒被停放的线程,使其重新进入调度队列,等待执行。
代码示例
use std::thread;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
fn main() {
let flag = Arc::new(AtomicBool::new(false));
let flag_clone = flag.clone();
let thread1 = thread::spawn(move || {
// 线程1 等待flag变为true
while!flag_clone.load(Ordering::Relaxed) {
thread::park();
}
println!("Thread 1 resumed and doing its work.");
});
// 主线程模拟一些工作
thread::sleep(std::time::Duration::from_secs(2));
// 主线程设置flag为true 唤醒线程1
flag.store(true, Ordering::Relaxed);
thread1.unpark();
if let Err(e) = thread1.join() {
println!("Thread 1 panicked: {:?}", e);
}
}
在这个示例中,thread1
线程会不断检查flag
的值,若为false
,则调用thread::park
暂停执行。主线程在等待2秒后,将flag
设置为true
,并调用thread1.unpark
唤醒thread1
线程,从而实现两个线程间的同步。