fast_able/fast_thread_pool/
lite.rs

1use std::sync::Arc;
2
3use crossbeam::atomic::AtomicCell;
4
5use super::TaskExecutor;
6
7/// Simple thread pool
8/// Used for quickly submitting tasks
9/// Only one thread, bound to only one core
10/// 简易线程池
11/// 用于快速提交任务
12/// 只有一个线程, 只绑定一个核心
13pub struct ThreadPoolLite {
14    pub thread: TaskExecutor,
15}
16
17impl ThreadPoolLite {
18    pub fn new() -> ThreadPoolLite {
19        let use_core = super::use_last_core("thread_lite");
20        let r = ThreadPoolLite {
21            thread: TaskExecutor::new(core_affinity::CoreId { id: use_core }, 49),
22        };
23        r
24    }
25
26    pub fn spawn<F>(&self, f: F)
27    where
28        F: FnOnce(),
29        F: Send + 'static,
30    {
31        self.thread.spawn(|_| f());
32    }
33}
34
35pub fn _test_thread_lite(test_count: u128) {
36    let pool = ThreadPoolLite::new();
37    std::thread::sleep(std::time::Duration::from_millis(200));
38    let com_time = Arc::new(AtomicCell::new(0_u128));
39    for _ in 0..test_count {
40        let now = std::time::Instant::now();
41        let com_time = com_time.clone();
42        pool.spawn(move || {
43            // println!("run _test_thread_lite i: {}", i);
44            let el = now.elapsed().as_nanos();
45            com_time.fetch_add(el);
46        });
47    }
48    println!("------------------------thread_lite 任务提交完成------------------------");
49    std::thread::sleep(std::time::Duration::from_secs(1));
50    println!(
51        "thread_lite test result: Average thread startup time: {:.3} micros\nthread_lite 测试结果: 线程开启平均耗时: {:.3} micros",
52        com_time.load() as f64 / test_count as f64 / 1000.0,
53        com_time.load() as f64 / test_count as f64 / 1000.0
54    );
55}
56
57#[test]
58pub fn test_cores_count() {
59    // 初始化日志
60    let _ = env_logger::try_init();
61
62    // 获取核心数并打印
63    let cores = crate::fast_thread_pool::CORES.clone();
64
65    // 使用 num_cpus 获取实际的 CPU 数量
66    let physical_cpus = num_cpus::get_physical();
67    let logical_cpus = num_cpus::get();
68
69    info!(
70        "物理CPU数量: {}, 逻辑CPU数量: {}, CORES获取的核心数: {}",
71        physical_cpus,
72        logical_cpus,
73        cores.len()
74    );
75
76    // 输出所有核心ID
77    info!(
78        "核心ID列表: {:?}",
79        cores.iter().map(|x| x.id).collect::<Vec<_>>()
80    );
81
82    // 验证核心数是否符合预期
83    assert!(cores.len() > 0, "核心数应该大于0");
84    assert!(
85        cores.len() >= physical_cpus,
86        "核心数应该大于等于物理CPU数量"
87    );
88
89    // 在有超线程技术的系统上,逻辑CPU数通常是物理CPU数的两倍
90    if logical_cpus > physical_cpus {
91        info!("系统支持超线程技术,每个物理核心有多个逻辑核心");
92    }
93}