面试题答案
一键面试- 使用原子操作实现停止标志的简述:
- 在Rust中,可以使用
std::sync::atomic::AtomicBool
来实现线程间共享的停止标志。AtomicBool
提供了原子操作方法,确保在多线程环境下对标志的读取和写入操作是线程安全的。负责监听用户输入的线程可以通过store
方法设置停止标志,而其他工作线程可以通过load
方法读取该标志,以决定是否继续工作。
- 在Rust中,可以使用
- 关键代码片段:
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
fn main() {
let stop_flag = Arc::new(AtomicBool::new(false));
let stop_flag_clone = stop_flag.clone();
// 监听用户输入的线程
let input_thread = thread::spawn(move || {
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
if input.trim() == "stop" {
stop_flag_clone.store(true, Ordering::SeqCst);
}
});
// 工作线程
let worker_thread = thread::spawn(move || {
while!stop_flag.load(Ordering::SeqCst) {
// 实际工作代码
println!("Working...");
thread::sleep(std::time::Duration::from_secs(1));
}
println!("Stopping work due to stop flag.");
});
input_thread.join().expect("Failed to join input thread");
worker_thread.join().expect("Failed to join worker thread");
}
在上述代码中:
Arc<AtomicBool>
用于在多个线程间共享AtomicBool
类型的停止标志。Arc
(原子引用计数)允许在多个线程间安全地共享数据。AtomicBool
的store
方法用于设置停止标志,load
方法用于读取停止标志。Ordering::SeqCst
是一种较强的内存序,确保操作按顺序执行,以避免数据竞争和未定义行为。