rust 多线程分发数据

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();

}
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值