小弧光的博客

公众号:小弧光黑板报

导航

写一段rust代码,两个线程共享一个bool变量,一个写,一个读

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    // 创建一个布尔变量并用 Arc 和 Mutex 包装,使其可在多个线程间共享和修改
    let shared_bool = Arc::new(Mutex::new(false));

    // 克隆 Arc 变量,以便在两个线程之间共享
    let writer_shared_bool = Arc::clone(&shared_bool);
    let reader_shared_bool = Arc::clone(&shared_bool);

    // 创建写线程
    let writer_thread = thread::spawn(move || {
        // 在 Mutex 中修改布尔变量
        let mut data = writer_shared_bool.lock().unwrap();
        *data = true;
        println!("Writer thread wrote to the shared boolean variable");
    });

    // 创建读线程
    let reader_thread = thread::spawn(move || {
        // 在 Mutex 中读取布尔变量
        let data = reader_shared_bool.lock().unwrap();
        println!("Reader thread read from the shared boolean variable: {}", *data);
    });

    // 等待写线程和读线程完成
    writer_thread.join().unwrap();
    reader_thread.join().unwrap();
}

posted on 2024-01-29 10:55  小弧光  阅读(40)  评论(0编辑  收藏  举报