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    pub fn spawn_with_idx<F>(&self, f: F, thread_idx: usize)
48    where
49        F: FnOnce(),
50        F: Send + 'static,
51    {
52        self.thread[thread_idx].spawn(|_| f());
53        self.cur_run_core.store(thread_idx);
54    }
55
56    pub fn thread_count(&self) -> usize {
57        N
58    }
59}
60
61pub fn _test_ThreadPoolConstNum(test_count: u128) {
62    println!("------------------------start------------------------");
63    // println!("1%3: {}", 1 % 3);
64    // println!("2%3: {}", 2 % 3);
65    // println!("3%3: {}", 3 % 3);
66    // println!("4%3: {}", 4 % 3);
67    // println!("5%3: {}", 5 % 3);
68    // println!("6%3: {}", 6 % 3);
69    // println!("7%3: {}", 7 % 3);
70    // println!("8%3: {}", 8 % 3);
71
72    let pool = ThreadPoolConstNum::<5>::new();
73    std::thread::sleep(std::time::Duration::from_millis(200));
74    let com_time = Arc::new(AtomicCell::new(0_u128));
75    for _ in 0..test_count {
76        let com_time = com_time.clone();
77        let now = std::time::Instant::now();
78        pool.spawn(move || {
79            // println!("run _test_cur_index i: {}", i);
80            com_time.fetch_add(now.elapsed().as_nanos());
81        });
82    }
83    println!("------------------------ThreadPoolConstNum 任务提交完成------------------------");
84    std::thread::sleep(std::time::Duration::from_secs(1));
85    println!(
86        "ThreadPoolConstNum 线程开启平均耗时: {} ns",
87        com_time.load() as f64 / test_count as f64
88    );
89}