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