fast_able/fast_thread_pool/
const_num.rs1use std::sync::Arc;
2
3use core_affinity::CoreId;
4use crossbeam::atomic::AtomicCell;
5
6use super::TaskExecutor;
7
8pub 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 let use_cores = super::use_last_core2("ThreadPoolConstNum", N);
24
25 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 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 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}