rust多线程使用

参考文档

无畏并发

大任务切成子任务派发到子线程处理

版本一

#![feature(iterator_step_by)]
#[macro_use]
extern crate log;
#[macro_use]
extern crate scopeguard;
extern crate num_cpus;
extern crate log4rs;

use std::time;
use std::thread;
use std::sync::{Arc, Mutex};

fn sub_thread_func(task_list: Arc<Vec<i32>>, thread_index: usize, thread_count: usize, finished_num: Arc<Mutex<i64>>) {
    info!("线程{} 启动", thread_index);
    defer!( info!("线程{} 退出", thread_index) );

    //使用类似Python中list步长的方法来进行遍历
    for task_index in (thread_index..task_list.len()).step_by(thread_count) {
        let task_id = task_list[task_index];
        {
            let mut fnum = finished_num.lock().unwrap();
            *fnum += 1;
            info!("线程{} 执行任务{}  已完成{}", thread_index, task_id, fnum);
        }
        thread::sleep(time::Duration::from_millis(500));
    }
}


fn main() {
    log4rs::init_file("log4rs.yaml", Default::default()).unwrap();

    //获取cpu的物理核心数量
    //let thread_count = num_cpus::get_physical();

    //获取cpu的逻辑核心数量
    //let thread_count = num_cpus::get();

    let thread_count = 4;


    //待处理的任务队列
    let task_list = Arc::new(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

    //打印出耗费时间
    let time_start = time::Instant::now();
    info!("run start>>>>>");
    defer!({
        let elapsed = time_start.elapsed();
        info!("run finish<<<<< ({}s {}ms)",elapsed.as_secs(), (elapsed.subsec_nanos() / 1_000_000) as u64);
    });

    //存储线程句柄
    let mut thread_handlers = Vec::new();

    //统计已完成的数量
    let finished_num = Arc::new(Mutex::new(0i64));

    //一次性均匀派发到各个子线程处理
    for thread_index in 0..thread_count {
        let task_list = task_list.clone();
        let finished_num = finished_num.clone();

        thread_handlers.push(thread::spawn(move || {
            sub_thread_func(task_list, thread_index, thread_count, finished_num);
        }))
    }

    //等待所有子进程退出
    for handler in thread_handlers {
        handler.join();
    }
}

转载于:https://my.oschina.net/u/111188/blog/1559692

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值