recoverable_thread_pool/thread_pool/sync/
impl.rs1use crate::*;
2use recoverable_spawn::sync::*;
3
4impl ThreadPool {
5 pub fn new(size: usize) -> ThreadPool {
6 let (sender, receiver) = mpsc::channel();
7 let receiver: Arc<Mutex<Receiver<ThreadPoolJob>>> = Arc::new(Mutex::new(receiver));
8 let mut workers: Vec<Worker> = Vec::with_capacity(size);
9 let mut id: usize = 0;
10 loop {
11 if id >= size {
12 break;
13 }
14 let worker: Option<Worker> = Worker::new(id, Arc::clone(&receiver));
15 if worker.is_some() {
16 workers.push(worker.unwrap_or_default());
17 id += 1;
18 }
19 }
20 ThreadPool { workers, sender }
21 }
22
23 pub fn execute<F>(&self, job: F) -> SendResult
24 where
25 F: RecoverableFunction,
26 {
27 let job_with_handler: ThreadPoolJob = Box::new(move || {
28 let _ = run_function(job);
29 });
30 self.sender.send(job_with_handler)
31 }
32
33 pub fn execute_with_catch<F, E>(&self, job: F, handle_error: E) -> SendResult
34 where
35 F: RecoverableFunction,
36 E: ErrorHandlerFunction,
37 {
38 let job_with_handler: ThreadPoolJob = Box::new(move || {
39 if let Err(err) = run_function(job) {
40 let err_string: String = spawn_error_to_string(&err);
41 let _ = run_error_handle_function(handle_error, &err_string);
42 }
43 });
44 self.sender.send(job_with_handler)
45 }
46
47 pub fn execute_with_catch_finally<F, E, L>(
48 &self,
49 job: F,
50 handle_error: E,
51 finally: L,
52 ) -> SendResult
53 where
54 F: RecoverableFunction,
55 E: ErrorHandlerFunction,
56 L: RecoverableFunction,
57 {
58 let job_with_handler: ThreadPoolJob = Box::new(move || {
59 if let Err(err) = run_function(job) {
60 let err_string: String = spawn_error_to_string(&err);
61 let _ = run_error_handle_function(handle_error, &err_string);
62 }
63 let _ = run_function(finally);
64 });
65 self.sender.send(job_with_handler)
66 }
67}