無畏併發html
#![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(); } }