小弧光的博客

公众号:小弧光黑板报

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

统计

写一段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   小弧光  阅读(73)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
历史上的今天:
2023-01-29 Graphite: a vision for the future of 2D content creation.
点击右上角即可分享
微信分享提示