MST

星途 面试题库

面试题:Rust原子操作在停止标志场景中的基础应用

在Rust中,假设你要实现一个多线程程序,其中一个线程负责监听用户输入来设置停止标志,其他线程根据这个停止标志来决定是否继续工作。请简述如何使用原子操作来实现这个停止标志,并给出关键代码片段。
11.9万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
  1. 使用原子操作实现停止标志的简述
    • 在Rust中,可以使用std::sync::atomic::AtomicBool来实现线程间共享的停止标志。AtomicBool提供了原子操作方法,确保在多线程环境下对标志的读取和写入操作是线程安全的。负责监听用户输入的线程可以通过store方法设置停止标志,而其他工作线程可以通过load方法读取该标志,以决定是否继续工作。
  2. 关键代码片段
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(原子引用计数)允许在多个线程间安全地共享数据。
  • AtomicBoolstore方法用于设置停止标志,load方法用于读取停止标志。Ordering::SeqCst是一种较强的内存序,确保操作按顺序执行,以避免数据竞争和未定义行为。