fast_able/fast_thread_pool/
const_num.rs

1use std::sync::Arc;
2
3use core_affinity::CoreId;
4use crossbeam::atomic::AtomicCell;
5
6use super::TaskExecutor;
7
8/// 简易线程池
9/// 用于快速提交任务
10/// 只有一个线程, 只绑定一个核心
11pub struct ThreadPoolConstNum<const N: usize> {
12    thread: [TaskExecutor; N],
13    cur_run_core: AtomicCell<usize>,
14}
15
16impl<const N: usize> ThreadPoolConstNum<N> {
17    pub fn new() -> Self {
18        // 使用 use_last_core2 获取指定数量的 CPU 核心
19        let use_cores = super::use_last_core2("ThreadPoolConstNum", N);
20        
21        // 创建线程执行器
22        let mut threads = vec![];
23        for core_id in &use_cores {
24            threads.push(TaskExecutor::new(CoreId { id: *core_id }, 49));
25        }
26
27        ThreadPoolConstNum {
28            thread: threads
29                .try_into()
30                .expect("ThreadPoolLiteNum threads.try_into()"),
31            cur_run_core: 0.into(),
32        }
33    }
34
35    pub fn spawn<F>(&self, f: F)
36    where
37        F: FnOnce(),
38        F: Send + 'static,
39    {
40        let cur_index = self.cur_run_core.fetch_add(1);
41        self.thread[cur_index % N].spawn(|_| f());
42        if cur_index >= usize::MAX - N {
43            self.cur_run_core.store(0);
44        }
45    }
46}
47
48pub fn _test_ThreadPoolConstNum(test_count: u128) {
49    println!("------------------------start------------------------");
50    // println!("1%3: {}", 1 % 3);
51    // println!("2%3: {}", 2 % 3);
52    // println!("3%3: {}", 3 % 3);
53    // println!("4%3: {}", 4 % 3);
54    // println!("5%3: {}", 5 % 3);
55    // println!("6%3: {}", 6 % 3);
56    // println!("7%3: {}", 7 % 3);
57    // println!("8%3: {}", 8 % 3);
58
59    let pool = ThreadPoolConstNum::<5>::new();
60    std::thread::sleep(std::time::Duration::from_millis(200));
61    let com_time = Arc::new(AtomicCell::new(0_u128));
62    for _ in 0..test_count {
63        let com_time = com_time.clone();
64        let now = std::time::Instant::now();
65        pool.spawn(move || {
66            // println!("run _test_cur_index i: {}", i);
67            com_time.fetch_add(now.elapsed().as_nanos());
68        });
69    }
70    println!("------------------------ThreadPoolConstNum 任务提交完成------------------------");
71    std::thread::sleep(std::time::Duration::from_secs(1));
72    println!(
73        "ThreadPoolConstNum 线程开启平均耗时: {} ns",
74        com_time.load() as f64 / test_count as f64
75    );
76}