1use threadpool::ThreadPool;
2use std::thread;
3
4pub struct ThreadUtil {
5 pool: ThreadPool,
6}
7
8impl ThreadUtil {
9 pub fn new(thread_num: usize) -> Self {
14 let pool = threadpool::ThreadPool::new(thread_num);
15 Self { pool }
16 }
17
18 pub fn execute<F>(&self, task: F)
31 where
32 F: FnOnce() + Send + 'static,
33 {
34 self.pool.execute(task);
36 }
37
38 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}