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 多线程分发数据
最新推荐文章于 2024-08-25 10:20:18 发布