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> {
12 thread: [TaskExecutor; N],
13 cur_run_core: AtomicCell<usize>,
14}
15
16impl<const N: usize> ThreadPoolConstNum<N> {
17 pub fn new() -> Self {
18 let use_cores = super::use_last_core2("ThreadPoolConstNum", N);
20
21 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 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 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}