当前位置: 首页> 房产> 市场 > rust 多线程分发数据

rust 多线程分发数据

时间:2025/7/15 10:58:29来源:https://blog.csdn.net/cosx_/article/details/139781114 浏览次数:0次
use std::sync::{Arc, Mutex};
use std::collections::VecDeque;
use std::thread::{self, sleep};
use rand::Rng;
use std::time::Duration;fn main() {let list: Arc<Mutex<VecDeque<String>>> = Arc::new(Mutex::new(VecDeque::new()));// 创建修改线程let list_clone = list.clone();let mutator = thread::spawn(move || {let mut rng = rand::thread_rng();loop {let random_operation = rng.gen_range(0..3); // 随机选择操作:0-添加到前端,1-添加到后端,2-随机删除let value = rng.gen_range(1..101).to_string(); // 生成随机数作为值let mut list_guard = list_clone.lock().unwrap(); // 获取互斥锁的所有权match random_operation {0 => list_guard.push_front(value.clone()), // 添加到前端1 => list_guard.push_back(value.clone()),  // 添加到后端2 => {if let Some(_) = list_guard.pop_front() {} // 尝试从前端删除}_ => {}}drop(list_guard); // 显式释放锁thread::sleep(Duration::from_millis(100)); // 模拟操作之间的延迟}});// 创建查询线程let list_clone = list.clone();let observer = thread::spawn(move || {loop {let list_guard = list_clone.lock().unwrap(); // 获取互斥锁的所有权println!("Current state of the deque: {:?}", list_guard);drop(list_guard); // 显式释放锁thread::sleep(Duration::from_millis(500)); // 模拟查询之间的延迟}});// 这里我们让主线程等待,直到两个线程都完成let _ = mutator.join();let _ = observer.join();}
关键字:rust 多线程分发数据

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: