recoverable_thread_pool/thread_pool/sync/
impl.rs1use crate::*;
2use recoverable_spawn::sync::*;
3
4impl ThreadPool {
6 pub fn new(size: usize) -> ThreadPool {
16 let (sender, receiver) = mpsc::channel();
17 let receiver: Arc<Mutex<Receiver<ThreadPoolJob>>> = Arc::new(Mutex::new(receiver));
18 let mut workers: Vec<Worker> = Vec::with_capacity(size);
19 let mut id: usize = 0;
20 loop {
21 if id >= size {
22 break;
23 }
24 let worker: Option<Worker> = Worker::new(id, Arc::clone(&receiver));
25 if worker.is_some() {
26 workers.push(worker.unwrap_or_default());
27 id += 1;
28 }
29 }
30 ThreadPool { workers, sender }
31 }
32
33 pub fn execute<F>(&self, job: F) -> SendResult
43 where
44 F: RecoverableFunction,
45 {
46 let job_with_handler: ThreadPoolJob = Box::new(move || {
47 let _ = run_function(job);
48 });
49 self.sender.send(job_with_handler)
50 }
51
52 pub fn execute_with_catch<F, E>(&self, job: F, handle_error: E) -> SendResult
63 where
64 F: RecoverableFunction,
65 E: ErrorHandlerFunction,
66 {
67 let job_with_handler: ThreadPoolJob = Box::new(move || {
68 if let Err(err) = run_function(job) {
69 let err_string: String = spawn_error_to_string(&err);
70 let _ = run_error_handle_function(handle_error, &err_string);
71 }
72 });
73 self.sender.send(job_with_handler)
74 }
75
76 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 _ = run_error_handle_function(handle_error, &err_string);
102 }
103 let _ = run_function(finally);
104 });
105 self.sender.send(job_with_handler)
106 }
107}