rust多线程使用

原创
2017/11/02 10:56
阅读数 2.3K

参考文档

无畏并发

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

版本一

#![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();
    }
}
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部