dev_tool/
thread_util.rs

1use threadpool::ThreadPool;
2use std::thread;
3
4pub struct ThreadUtil {
5    pool: ThreadPool,
6}
7
8impl ThreadUtil {
9    /// 创建一个线程池,并执行任务
10    ///
11    /// # 参数
12    /// * `thread_num` - 线程池中的线程数量
13    pub fn new(thread_num: usize) -> Self {
14        let pool = threadpool::ThreadPool::new(thread_num);
15        Self { pool }
16    }
17
18    /// 执行一个任务函数
19    ///
20    /// 该函数将给定的任务提交到线程池中执行。任务必须是只执行一次的闭包,
21    /// 并且需要满足线程安全和生命周期要求。
22    ///
23    /// # 参数
24    ///
25    /// * `task` - 要执行的任务函数,必须实现FnOnce、Send和'static约束
26    ///
27    /// # 泛型参数
28    ///
29    /// * `F` - 任务函数的类型,必须满足FnOnce() + Send + 'static约束
30    pub fn execute<F>(&self, task: F)
31    where
32        F: FnOnce() + Send + 'static,
33    {
34        // 将任务委托给内部线程池执行
35        self.pool.execute(task);
36    }
37
38    /// 等待线程池中的所有任务执行完成
39    ///
40    /// 此函数会阻塞当前线程,直到线程池中的所有任务都执行完毕。
41    /// 调用此函数后,线程池将不再接受新的任务。
42    pub fn join(&self) {
43        self.pool.join();
44    }
45
46    pub fn spawn<F, T>(f: F) -> thread::JoinHandle<T>
47    where
48        F: FnOnce() -> T,
49        F: Send + 'static,
50        T: Send + 'static,
51    {
52        thread::spawn(f)
53    }
54    
55}
56
57#[cfg(test)]
58mod tests {
59
60    use super::*;
61
62    #[test]
63    fn it_works() {
64        let pool_util = ThreadUtil::new(4);
65        pool_util.execute(|| {
66            println!("Hello, world2!");
67        });
68        println!("Hello, world1!");
69        pool_util.join();
70        println!("Hello, world3!");
71    }
72}