寫一段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();
}
轉載請注明原文鏈接:http://www.rzrgm.cn/itfanr/p/17994054
公眾號:小弧光黑板報
浙公網安備 33010602011771號