Skip to main content

recoverable_thread_pool/thread_pool/
impl.rs

1use super::*;
2
3/// Sync implementation of thread pool operations.
4impl ThreadPool {
5    /// Creates a new thread pool with the specified number of workers.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - The number of worker threads to create.
10    ///
11    /// # Returns
12    ///
13    /// - `ThreadPool` - The new thread pool instance.
14    pub fn new(size: usize) -> ThreadPool {
15        let (sender, receiver) = mpsc::channel();
16        let receiver: Arc<Mutex<Receiver<ThreadPoolJob>>> = Arc::new(Mutex::new(receiver));
17        let mut workers: Vec<Worker> = Vec::with_capacity(size);
18        let mut id: usize = 0;
19        loop {
20            if id >= size {
21                break;
22            }
23            let worker: Option<Worker> = Worker::new(id, Arc::clone(&receiver));
24            if worker.is_some() {
25                workers.push(worker.unwrap_or_default());
26                id += 1;
27            }
28        }
29        ThreadPool { workers, sender }
30    }
31
32    /// Executes a synchronous job in the thread pool.
33    ///
34    /// # Arguments
35    ///
36    /// - `F` - The synchronous function to execute.
37    ///
38    /// # Returns
39    ///
40    /// - `SendResult` - Result of the job submission.
41    pub fn execute<F>(&self, job: F) -> SendResult
42    where
43        F: RecoverableFunction,
44    {
45        let job_with_handler: ThreadPoolJob = Box::new(move || {
46            let _: std::thread::Result<()> = run_function(job);
47        });
48        self.sender.send(job_with_handler)
49    }
50
51    /// Executes a synchronous job with error handling in the thread pool.
52    ///
53    /// # Arguments
54    ///
55    /// - `F` - The synchronous function to execute.
56    /// - `E` - The error handler function.
57    ///
58    /// # Returns
59    ///
60    /// - `SendResult` - Result of the job submission.
61    pub fn execute_with_catch<F, E>(&self, job: F, handle_error: E) -> SendResult
62    where
63        F: RecoverableFunction,
64        E: ErrorHandlerFunction,
65    {
66        let job_with_handler: ThreadPoolJob = Box::new(move || {
67            if let Err(err) = run_function(job) {
68                let err_string: String = spawn_error_to_string(&err);
69                let _: std::thread::Result<()> =
70                    run_error_handle_function(handle_error, &err_string);
71            }
72        });
73        self.sender.send(job_with_handler)
74    }
75
76    /// Executes a synchronous job with error handling and finalization in the thread pool.
77    ///
78    /// # Arguments
79    ///
80    /// - `F` - The synchronous function to execute.
81    /// - `E` - The error handler function.
82    /// - `L` - The finally handler function.
83    ///
84    /// # Returns
85    ///
86    /// - `SendResult` - Result of the job submission.
87    pub fn execute_with_catch_finally<F, E, L>(
88        &self,
89        job: F,
90        handle_error: E,
91        finally: L,
92    ) -> SendResult
93    where
94        F: RecoverableFunction,
95        E: ErrorHandlerFunction,
96        L: RecoverableFunction,
97    {
98        let job_with_handler: ThreadPoolJob = Box::new(move || {
99            if let Err(err) = run_function(job) {
100                let err_string: String = spawn_error_to_string(&err);
101                let _: std::thread::Result<()> =
102                    run_error_handle_function(handle_error, &err_string);
103            }
104            let _: std::thread::Result<()> = run_function(finally);
105        });
106        self.sender.send(job_with_handler)
107    }
108
109    /// Executes an async job in the thread pool.
110    ///
111    /// # Arguments
112    ///
113    /// - `F` - The async function to execute.
114    ///
115    /// # Returns
116    ///
117    /// - `SendResult` - Result of the job submission.
118    pub fn async_execute<F>(&self, job: F) -> SendResult
119    where
120        F: AsyncRecoverableFunction,
121    {
122        let job_with_handler = Box::new(move || {
123            Builder::new_current_thread()
124                .enable_all()
125                .build()
126                .unwrap()
127                .block_on(async move {
128                    let _: AsyncSpawnResult = async_run_function(move || async {
129                        job.call().await;
130                    })
131                    .await;
132                });
133        });
134        self.sender.send(job_with_handler)
135    }
136
137    /// Executes an async job with error handling in the thread pool.
138    ///
139    /// # Arguments
140    ///
141    /// - `F` - The async function to execute.
142    /// - `E` - The async error handler function.
143    ///
144    /// # Returns
145    ///
146    /// - `SendResult` - Result of the job submission.
147    pub fn async_execute_with_catch<F, E>(&self, job: F, handle_error: E) -> SendResult
148    where
149        F: AsyncRecoverableFunction,
150        E: AsyncErrorHandlerFunction,
151    {
152        let job_with_handler = Box::new(move || {
153            Builder::new_current_thread()
154                .enable_all()
155                .build()
156                .unwrap()
157                .block_on(async move {
158                    let run_result: AsyncSpawnResult = async_run_function(move || async {
159                        job.call().await;
160                    })
161                    .await;
162                    if let Err(err) = run_result {
163                        let err_string: String = tokio_error_to_string(&err);
164                        let _: AsyncSpawnResult = async_run_error_handle_function(
165                            move |err_str| async move {
166                                handle_error.call(err_str).await;
167                            },
168                            Arc::new(err_string),
169                        )
170                        .await;
171                    }
172                });
173        });
174        self.sender.send(job_with_handler)
175    }
176
177    /// Executes an async job with error handling and finalization in the thread pool.
178    ///
179    /// # Arguments
180    ///
181    /// - `F` - The async function to execute.
182    /// - `E` - The async error handler function.
183    /// - `L` - The async finally handler function.
184    ///
185    /// # Returns
186    ///
187    /// - `SendResult` - Result of the job submission.
188    pub fn async_execute_with_catch_finally<F, E, L>(
189        &self,
190        job: F,
191        handle_error: E,
192        finally: L,
193    ) -> SendResult
194    where
195        F: AsyncRecoverableFunction,
196        E: AsyncErrorHandlerFunction,
197        L: AsyncRecoverableFunction,
198    {
199        let job_with_handler = Box::new(move || {
200            Builder::new_current_thread()
201                .enable_all()
202                .build()
203                .unwrap()
204                .block_on(async move {
205                    let run_result: AsyncSpawnResult = async_run_function(move || async {
206                        job.call().await;
207                    })
208                    .await;
209                    if let Err(err) = run_result {
210                        let err_string: String = tokio_error_to_string(&err);
211                        let _: AsyncSpawnResult = async_run_error_handle_function(
212                            move |err_str| async move {
213                                handle_error.call(err_str).await;
214                            },
215                            Arc::new(err_string),
216                        )
217                        .await;
218                    }
219                    let _: AsyncSpawnResult = async_run_function(move || async {
220                        finally.call().await;
221                    })
222                    .await;
223                });
224        });
225        self.sender.send(job_with_handler)
226    }
227}