Skip to main content

rumtk_core/
threading.rs

1/*
2 * rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
3 * This toolkit aims to be reliable, simple, performant, and standards compliant.
4 * Copyright (C) 2025  Luis M. Santos, M.D.
5 * Copyright (C) 2025  MedicalMasses L.L.C.
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
20 */
21
22///
23/// This module provides all the primitives needed to build a multithreaded application.
24///
25pub mod thread_primitives {
26    use crate::cache::{new_cache, LazyRUMCache};
27    use std::sync::Arc;
28    pub use tokio::io;
29    pub use tokio::io::{AsyncReadExt, AsyncWriteExt};
30    use tokio::runtime::Runtime as TokioRuntime;
31    pub use tokio::sync::{
32        Mutex as AsyncMutex, MutexGuard as AsyncMutexGuard, RwLock as AsyncRwLock, RwLockReadGuard,
33        RwLockWriteGuard,
34    };
35    /**************************** Globals **************************************/
36    pub static mut RT_CACHE: TokioRtCache = new_cache();
37    /**************************** Helpers ***************************************/
38    pub fn init_cache(threads: &usize) -> SafeTokioRuntime {
39        let mut builder = tokio::runtime::Builder::new_multi_thread();
40        builder.worker_threads(*threads);
41        builder.enable_all();
42        match builder.build() {
43            Ok(handle) => Arc::new(handle),
44            Err(e) => panic!(
45                "Unable to initialize threading tokio runtime because {}!",
46                &e
47            ),
48        }
49    }
50
51    /**************************** Types ***************************************/
52    pub type SafeTokioRuntime = Arc<TokioRuntime>;
53    pub type TokioRtCache = LazyRUMCache<usize, SafeTokioRuntime>;
54}
55
56pub mod threading_manager {
57    use crate::cache::LazyRUMCacheValue;
58    use crate::core::{RUMResult, RUMVec};
59    use crate::strings::rumtk_format;
60    use crate::threading::thread_primitives::SafeTokioRuntime;
61    use crate::threading::threading_functions::async_sleep;
62    use crate::types::{RUMHashMap, RUMID};
63    use crate::{rumtk_init_threads, rumtk_resolve_task, rumtk_spawn_task, threading};
64    use std::future::Future;
65    use std::sync::Arc;
66    pub use std::sync::RwLock as SyncRwLock;
67    use tokio::sync::RwLock as AsyncRwLock;
68    use tokio::task::JoinHandle;
69
70    const DEFAULT_SLEEP_DURATION: f32 = 0.001f32;
71    const DEFAULT_TASK_CAPACITY: usize = 100;
72
73    pub type TaskItems<T> = RUMVec<T>;
74    /// This type aliases a vector of T elements that will be used for passing arguments to the task processor.
75    pub type TaskArgs<T> = TaskItems<T>;
76    /// Function signature defining the interface of task processing logic.
77    pub type SafeTaskArgs<T> = Arc<AsyncRwLock<TaskItems<T>>>;
78    pub type AsyncTaskHandle<R> = JoinHandle<TaskResult<R>>;
79    pub type AsyncTaskHandles<R> = Vec<AsyncTaskHandle<R>>;
80    //pub type TaskProcessor<T, R, Fut: Future<Output = TaskResult<R>>> = impl FnOnce(&SafeTaskArgs<T>) -> Fut;
81    pub type TaskID = RUMID;
82
83    #[derive(Debug, Clone, Default)]
84    pub struct Task<R> {
85        pub id: TaskID,
86        pub finished: bool,
87        pub result: Option<R>,
88    }
89
90    pub type SafeTask<R> = Arc<Task<R>>;
91    type SafeInternalTask<R> = Arc<SyncRwLock<Task<R>>>;
92    pub type TaskTable<R> = RUMHashMap<TaskID, SafeInternalTask<R>>;
93    pub type SafeAsyncTaskTable<R> = Arc<AsyncRwLock<TaskTable<R>>>;
94    pub type SafeSyncTaskTable<R> = Arc<SyncRwLock<TaskTable<R>>>;
95    pub type TaskBatch = RUMVec<TaskID>;
96    /// Type to use to define how task results are expected to be returned.
97    pub type TaskResult<R> = RUMResult<SafeTask<R>>;
98    pub type TaskResults<R> = TaskItems<TaskResult<R>>;
99    pub type TaskRuntime = LazyRUMCacheValue<SafeTokioRuntime>;
100
101    ///
102    /// Manages asynchronous tasks submitted as micro jobs from synchronous code. This type essentially
103    /// gives the multithreading, asynchronous superpowers to synchronous logic.
104    ///
105    /// ## Example Usage
106    ///
107    /// ```
108    /// use std::sync::{Arc};
109    /// use tokio::sync::RwLock as AsyncRwLock;
110    /// use rumtk_core::core::RUMResult;
111    /// use rumtk_core::strings::RUMString;
112    /// use rumtk_core::threading::threading_manager::{SafeTaskArgs, TaskItems, TaskManager};
113    /// use rumtk_core::{rumtk_create_task, };
114    ///
115    /// let expected = vec![
116    ///     RUMString::from("Hello"),
117    ///     RUMString::from("World!"),
118    ///     RUMString::from("Overcast"),
119    ///     RUMString::from("and"),
120    ///     RUMString::from("Sad"),
121    ///  ];
122    ///
123    /// type TestResult = RUMResult<Vec<RUMString>>;
124    /// let mut queue: TaskManager<TestResult> = TaskManager::new(&5).unwrap();
125    ///
126    /// let locked_args = AsyncRwLock::new(expected.clone());
127    /// let task_args = SafeTaskArgs::<RUMString>::new(locked_args);
128    /// let processor = rumtk_create_task!(
129    ///     async |args: &SafeTaskArgs<RUMString>| -> TestResult {
130    ///         let owned_args = Arc::clone(args);
131    ///         let locked_args = owned_args.read().await;
132    ///         let mut results = TaskItems::<RUMString>::with_capacity(locked_args.len());
133    ///
134    ///         for arg in locked_args.iter() {
135    ///             results.push(RUMString::new(arg));
136    ///         }
137    ///
138    ///         Ok(results)
139    ///     },
140    ///     task_args
141    /// );
142    ///
143    /// queue.add_task::<_>(processor);
144    /// let results = queue.wait();
145    ///
146    /// let mut result_data = Vec::<RUMString>::with_capacity(5);
147    /// for r in results {
148    ///     for v in r.unwrap().result.clone().unwrap().iter() {
149    ///         for value in v.iter() {
150    ///             result_data.push(value.clone());
151    ///         }
152    ///     }
153    ///  }
154    ///
155    /// assert_eq!(result_data, expected, "Results do not match expected!");
156    ///
157    /// ```
158    ///
159    #[derive(Debug, Clone, Default)]
160    pub struct TaskManager<R> {
161        tasks: SafeSyncTaskTable<R>,
162        workers: usize,
163    }
164
165    impl<R> TaskManager<R>
166    where
167        R: Sync + Send + Clone + 'static,
168    {
169        ///
170        /// This method creates a [`TaskQueue`] instance using sensible defaults.
171        ///
172        /// The `threads` field is computed from the number of cores present in system.
173        ///
174        pub fn default() -> RUMResult<TaskManager<R>> {
175            Self::new(&threading::threading_functions::get_default_system_thread_count())
176        }
177
178        ///
179        /// Creates an instance of [`ThreadedTaskQueue<T, R>`] in the form of [`SafeThreadedTaskQueue<T, R>`].
180        /// Expects you to provide the count of threads to spawn and the microtask queue size
181        /// allocated by each thread.
182        ///
183        /// This method calls [`Self::with_capacity()`] for the actual object creation.
184        /// The main queue capacity is pre-allocated to [`DEFAULT_QUEUE_CAPACITY`].
185        ///
186        pub fn new(worker_num: &usize) -> RUMResult<TaskManager<R>> {
187            let tasks = SafeSyncTaskTable::<R>::new(SyncRwLock::new(TaskTable::with_capacity(
188                DEFAULT_TASK_CAPACITY,
189            )));
190            Ok(TaskManager::<R> {
191                tasks,
192                workers: worker_num.to_owned(),
193            })
194        }
195
196        ///
197        /// Add a task to the processing queue. The idea is that you can queue a processor function
198        /// and list of args that will be picked up by one of the threads for processing.
199        ///
200        /// This is the async counterpart
201        ///
202        pub async fn add_task_async<F>(&mut self, task: F) -> TaskID
203        where
204            F: Future<Output = R> + Send + Sync + 'static,
205            F::Output: Send + Sized + 'static,
206        {
207            let id = TaskID::new_v4();
208            Self::_add_task_async(id.clone(), self.tasks.clone(), task).await
209        }
210
211        ///
212        /// See [add_task](Self::add_task)
213        ///
214        /// Unlike `add_task`, this method does not block which is key to avoiding panicking
215        /// the tokio runtim if trying to add task to queue from a normal function called from an
216        /// async environment.
217        ///
218        /// ## Example
219        ///
220        /// ```
221        /// use rumtk_core::threading::threading_manager::{TaskManager};
222        /// use rumtk_core::{rumtk_init_threads, strings::rumtk_format};
223        /// use std::sync::{Arc};
224        /// use tokio::sync::Mutex;
225        ///
226        /// type JobManager = Arc<Mutex<TaskManager<usize>>>;
227        ///
228        /// async fn called_fn() -> usize {
229        ///     5
230        /// }
231        ///
232        /// fn push_job(manager: &mut TaskManager<usize>) -> usize {
233        ///     manager.spawn_task(called_fn());
234        ///     1
235        /// }
236        ///
237        /// async fn call_sync_fn(mut manager: JobManager) -> usize {
238        ///     let mut owned = manager.lock().await;
239        ///     push_job(&mut owned)
240        /// }
241        ///
242        /// let workers = 5;
243        /// let rt = rumtk_init_threads!(&workers);
244        /// let mut manager = Arc::new(Mutex::new(TaskManager::new(&workers).unwrap()));
245        ///
246        /// manager.blocking_lock().spawn_task(call_sync_fn(manager.clone()));
247        ///
248        /// let result_raw = manager.blocking_lock().wait();
249        ///
250        /// ```
251        ///
252        pub fn spawn_task<F>(&mut self, task: F) -> TaskID
253        where
254            F: Future<Output = R> + Send + Sync + 'static,
255            F::Output: Send + Sized + 'static,
256        {
257            let id = TaskID::new_v4();
258            let rt = rumtk_init_threads!(&self.workers);
259            rumtk_spawn_task!(
260                rt,
261                Self::_add_task_async(id.clone(), self.tasks.clone(), task)
262            );
263            id
264        }
265
266        ///
267        /// See [add_task](Self::add_task)
268        ///
269        pub fn add_task<F>(&mut self, task: F) -> TaskID
270        where
271            F: Future<Output = R> + Send + Sync + 'static,
272            F::Output: Send + Sized + 'static,
273        {
274            let rt = rumtk_init_threads!(&self.workers);
275            rumtk_resolve_task!(rt, self.add_task_async(task))
276        }
277
278        async fn _add_task_async<F>(id: TaskID, tasks: SafeSyncTaskTable<R>, task: F) -> TaskID
279        where
280            F: Future<Output = R> + Send + Sync + 'static,
281            F::Output: Send + Sized + 'static,
282        {
283            let mut safe_task = Arc::new(SyncRwLock::new(Task::<R> {
284                id: id.clone(),
285                finished: false,
286                result: None,
287            }));
288            tasks.write().unwrap().insert(id.clone(), safe_task.clone());
289
290            let task_wrapper = async move || {
291                // Run the task
292                let result = task.await;
293
294                // Cleanup task
295                let mut lock = safe_task.write().unwrap();
296                lock.result = Some(result);
297                lock.finished = true;
298            };
299
300            tokio::spawn(task_wrapper());
301
302            id
303        }
304
305        ///
306        /// See [wait_async](Self::wait_async)
307        ///
308        pub fn wait(&mut self) -> TaskResults<R> {
309            let rt = rumtk_init_threads!(&self.workers);
310            rumtk_resolve_task!(rt, self.wait_async())
311        }
312
313        ///
314        /// See [wait_on_batch_async](Self::wait_on_batch_async)
315        ///
316        pub fn wait_on_batch(&mut self, tasks: &TaskBatch) -> TaskResults<R> {
317            let rt = rumtk_init_threads!(&self.workers);
318            rumtk_resolve_task!(rt, self.wait_on_batch_async(&tasks))
319        }
320
321        ///
322        /// See [wait_on_async](Self::wait_on_async)
323        ///
324        pub fn wait_on(&mut self, task_id: &TaskID) -> TaskResult<R> {
325            let rt = rumtk_init_threads!(&self.workers);
326            rumtk_resolve_task!(rt, self.wait_on_async(&task_id))
327        }
328
329        ///
330        /// This method waits until a queued task with [TaskID](TaskID) has been processed from the main queue.
331        ///
332        /// We poll the status of the task every [DEFAULT_SLEEP_DURATION](DEFAULT_SLEEP_DURATION) ms.
333        ///
334        /// Upon completion,
335        ///
336        /// 2. Return the result ([TaskResults<R>](TaskResults)).
337        ///
338        /// This operation consumes the task.
339        ///
340        /// ### Note:
341        /// ```text
342        ///     Results returned here are not guaranteed to be in the same order as the order in which
343        ///     the tasks were queued for work. You will need to pass a type as T that automatically
344        ///     tracks its own id or has a way for you to resort results.
345        /// ```
346        pub async fn wait_on_async(&mut self, task_id: &TaskID) -> TaskResult<R> {
347            let task = match self.tasks.write().unwrap().remove(task_id) {
348                Some(task) => task.clone(),
349                None => return Err(rumtk_format!("No task with id {}", task_id)),
350            };
351
352            while !task.read().unwrap().finished {
353                async_sleep(DEFAULT_SLEEP_DURATION).await;
354            }
355
356            let x = Ok(Arc::new(task.write().unwrap().clone()));
357            x
358        }
359
360        ///
361        /// This method waits until a set of queued tasks with [TaskID](TaskID) has been processed from the main queue.
362        ///
363        /// We poll the status of the task every [DEFAULT_SLEEP_DURATION](DEFAULT_SLEEP_DURATION) ms.
364        ///
365        /// Upon completion,
366        ///
367        /// 1. We collect the results generated (if any).
368        /// 2. Return the list of results ([TaskResults<R>](TaskResults)).
369        ///
370        /// ### Note:
371        /// ```text
372        ///     Results returned here are not guaranteed to be in the same order as the order in which
373        ///     the tasks were queued for work. You will need to pass a type as T that automatically
374        ///     tracks its own id or has a way for you to resort results.
375        /// ```
376        pub async fn wait_on_batch_async(&mut self, tasks: &TaskBatch) -> TaskResults<R> {
377            let mut results = TaskResults::<R>::default();
378            for task in tasks {
379                results.push(self.wait_on_async(task).await);
380            }
381            results
382        }
383
384        ///
385        /// This method waits until all queued tasks have been processed from the main queue.
386        ///
387        /// We poll the status of the main queue every [DEFAULT_SLEEP_DURATION](DEFAULT_SLEEP_DURATION) ms.
388        ///
389        /// Upon completion,
390        ///
391        /// 1. We collect the results generated (if any).
392        /// 2. We reset the main task and result internal queue states.
393        /// 3. Return the list of results ([TaskResults<R>](TaskResults)).
394        ///
395        /// This operation consumes all the tasks.
396        ///
397        /// ### Note:
398        /// ```text
399        ///     Results returned here are not guaranteed to be in the same order as the order in which
400        ///     the tasks were queued for work. You will need to pass a type as T that automatically
401        ///     tracks its own id or has a way for you to resort results.
402        /// ```
403        pub async fn wait_async(&mut self) -> TaskResults<R> {
404            let task_batch = self
405                .tasks
406                .read()
407                .unwrap()
408                .keys()
409                .cloned()
410                .collect::<Vec<_>>();
411            self.wait_on_batch_async(&task_batch).await
412        }
413
414        ///
415        /// Check if all work has been completed from the task queue.
416        ///
417        /// ## Examples
418        ///
419        /// ### Sync Usage
420        ///
421        ///```
422        /// use rumtk_core::threading::threading_manager::TaskManager;
423        ///
424        /// let manager = TaskManager::<usize>::new(&4).unwrap();
425        ///
426        /// let all_done = manager.is_all_completed();
427        ///
428        /// assert_eq!(all_done, true, "Empty TaskManager reports tasks are not completed!");
429        ///
430        /// ```
431        ///
432        pub fn is_all_completed(&self) -> bool {
433            let rt = rumtk_init_threads!(&self.workers);
434            rumtk_resolve_task!(rt, TaskManager::<R>::is_all_completed_async(self))
435        }
436
437        pub async fn is_all_completed_async(&self) -> bool {
438            for (_, task) in self.tasks.read().unwrap().iter() {
439                if !task.read().unwrap().finished {
440                    return false;
441                }
442            }
443
444            true
445        }
446
447        ///
448        /// Check if a task completed
449        ///
450        pub fn is_finished(&self, id: &TaskID) -> bool {
451            match self.tasks.read().unwrap().get(id) {
452                Some(t) => t.read().unwrap().finished,
453                None => false,
454            }
455        }
456
457        pub async fn is_finished_async(&self, id: &TaskID) -> bool {
458            match self.tasks.read().unwrap().get(id) {
459                Some(task) => task.read().unwrap().finished,
460                None => true,
461            }
462        }
463
464        ///
465        /// Alias for [wait](TaskManager::wait).
466        ///
467        fn gather(&mut self) -> TaskResults<R> {
468            self.wait()
469        }
470    }
471}
472
473///
474/// This module contains a few helper.
475///
476/// For example, you can find a function for determining number of threads available in system.
477/// The sleep family of functions are also here.
478///
479pub mod threading_functions {
480    use num_cpus;
481    use std::thread::{available_parallelism, sleep as std_sleep};
482    use std::time::Duration;
483    use tokio::time::sleep as tokio_sleep;
484
485    pub const NANOS_PER_SEC: u64 = 1000000000;
486    pub const MILLIS_PER_SEC: u64 = 1000;
487    pub const MICROS_PER_SEC: u64 = 1000000;
488
489    pub fn get_default_system_thread_count() -> usize {
490        let cpus: usize = num_cpus::get();
491        let parallelism = match available_parallelism() {
492            Ok(n) => n.get(),
493            Err(_) => 0,
494        };
495
496        if parallelism >= cpus {
497            parallelism
498        } else {
499            cpus
500        }
501    }
502
503    pub fn sleep(s: f32) {
504        let ns = s * NANOS_PER_SEC as f32;
505        let rounded_ns = ns.round() as u64;
506        let duration = Duration::from_nanos(rounded_ns);
507        std_sleep(duration);
508    }
509
510    pub async fn async_sleep(s: f32) {
511        let ns = s * NANOS_PER_SEC as f32;
512        let rounded_ns = ns.round() as u64;
513        let duration = Duration::from_nanos(rounded_ns);
514        tokio_sleep(duration).await;
515    }
516}
517
518///
519/// Main API for interacting with the threading back end. Remember, we use tokio as our executor.
520/// This means that by default, all jobs sent to the thread pool have to be async in nature.
521/// These macros make handling of these jobs at the sync/async boundary more convenient.
522///
523pub mod threading_macros {
524    use crate::threading::thread_primitives;
525    use crate::threading::threading_manager::SafeTaskArgs;
526
527    ///
528    /// First, let's make sure we have *tokio* initialized at least once. The runtime created here
529    /// will be saved to the global context so the next call to this macro will simply grab a
530    /// reference to the previously initialized runtime.
531    ///
532    /// Passing nothing will default to initializing a runtime using the default number of threads
533    /// for this system. This is typically equivalent to number of cores/threads for your CPU.
534    ///
535    /// Passing `threads` number will yield a runtime that allocates that many threads.
536    ///
537    ///
538    /// ## Examples
539    ///
540    /// ```
541    ///     use rumtk_core::{rumtk_init_threads, rumtk_resolve_task, rumtk_create_task_args, rumtk_create_task, rumtk_spawn_task};
542    ///     use rumtk_core::core::RUMResult;
543    ///     use rumtk_core::threading::threading_manager::SafeTaskArgs;
544    ///
545    ///     async fn test(args: &SafeTaskArgs<i32>) -> RUMResult<Vec<i32>> {
546    ///         let mut result = Vec::<i32>::new();
547    ///         for arg in args.read().await.iter() {
548    ///             result.push(*arg);
549    ///         }
550    ///         Ok(result)
551    ///     }
552    ///
553    ///     let rt = rumtk_init_threads!();                                      // Creates runtime instance
554    ///     let args = rumtk_create_task_args!(1);                               // Creates a vector of i32s
555    ///     let task = rumtk_create_task!(test, args);                           // Creates a standard task which consists of a function or closure accepting a Vec<T>
556    ///     let result = rumtk_resolve_task!(&rt, rumtk_spawn_task!(&rt, task)); // Spawn's task and waits for it to conclude.
557    /// ```
558    ///
559    /// ```
560    ///     use rumtk_core::{rumtk_init_threads, rumtk_resolve_task, rumtk_create_task_args, rumtk_create_task, rumtk_spawn_task};
561    ///     use rumtk_core::core::RUMResult;
562    ///     use rumtk_core::threading::threading_manager::SafeTaskArgs;
563    ///
564    ///     async fn test(args: &SafeTaskArgs<i32>) -> RUMResult<Vec<i32>> {
565    ///         let mut result = Vec::<i32>::new();
566    ///         for arg in args.read().await.iter() {
567    ///             result.push(*arg);
568    ///         }
569    ///         Ok(result)
570    ///     }
571    ///
572    ///     let thread_count: usize = 10;
573    ///     let rt = rumtk_init_threads!(&thread_count);
574    ///     let args = rumtk_create_task_args!(1);
575    ///     let task = rumtk_create_task!(test, args);
576    ///     let result = rumtk_resolve_task!(&rt, rumtk_spawn_task!(&rt, task));
577    /// ```
578    #[macro_export]
579    macro_rules! rumtk_init_threads {
580        ( ) => {{
581            use $crate::rumtk_cache_fetch;
582            use $crate::threading::thread_primitives::{init_cache, RT_CACHE};
583            use $crate::threading::threading_functions::get_default_system_thread_count;
584            let rt = rumtk_cache_fetch!(
585                &mut RT_CACHE,
586                &get_default_system_thread_count(),
587                init_cache
588            );
589            rt
590        }};
591        ( $threads:expr ) => {{
592            use $crate::rumtk_cache_fetch;
593            use $crate::threading::thread_primitives::{init_cache, RT_CACHE};
594            let rt = rumtk_cache_fetch!(&raw mut RT_CACHE, $threads, init_cache);
595            rt
596        }};
597    }
598
599    ///
600    /// Puts task onto the runtime queue.
601    ///
602    /// The parameters to this macro are a reference to the runtime (`rt`) and a future (`func`).
603    ///
604    /// The return is a [thread_primitives::JoinHandle<T>] instance. If the task was a standard
605    /// framework task, you will get [thread_primitives::AsyncTaskHandle] instead.
606    ///
607    #[macro_export]
608    macro_rules! rumtk_spawn_task {
609        ( $func:expr ) => {{
610            let rt = rumtk_init_threads!();
611            rt.spawn($func)
612        }};
613        ( $rt:expr, $func:expr ) => {{
614            $rt.spawn($func)
615        }};
616    }
617
618    ///
619    /// Using the initialized runtime, wait for the future to resolve in a thread blocking manner!
620    ///
621    /// If you pass a reference to the runtime (`rt`) and an async closure (`func`), we await the
622    /// async closure without passing any arguments.
623    ///
624    /// You can pass a third argument to this macro in the form of any number of arguments (`arg_item`).
625    /// In such a case, we pass those arguments to the call on the async closure and await on results.
626    ///
627    #[macro_export]
628    macro_rules! rumtk_wait_on_task {
629        ( $rt:expr, $func:expr ) => {{
630            $rt.block_on(async move {
631                $func().await
632            })
633        }};
634        ( $rt:expr, $func:expr, $($arg_items:expr),+ ) => {{
635            $rt.block_on(async move {
636                $func($($arg_items),+).await
637            })
638        }};
639    }
640
641    ///
642    /// This macro awaits a future.
643    ///
644    /// The arguments are a reference to the runtime (`rt) and a future.
645    ///
646    /// If there is a result, you will get the result of the future.
647    ///
648    /// ## Examples
649    ///
650    /// ```
651    ///     use rumtk_core::{rumtk_init_threads, rumtk_resolve_task, rumtk_create_task_args, rumtk_create_task, rumtk_spawn_task};
652    ///     use rumtk_core::core::RUMResult;
653    ///     use rumtk_core::threading::threading_manager::SafeTaskArgs;
654    ///
655    ///     async fn test(args: &SafeTaskArgs<i32>) -> RUMResult<Vec<i32>> {
656    ///         let mut result = Vec::<i32>::new();
657    ///         for arg in args.read().await.iter() {
658    ///             result.push(*arg);
659    ///         }
660    ///         Ok(result)
661    ///     }
662    ///
663    ///     let rt = rumtk_init_threads!();
664    ///     let args = rumtk_create_task_args!(1);
665    ///     let task = rumtk_create_task!(test, args);
666    ///     let result = rumtk_resolve_task!(&rt, rumtk_spawn_task!(&rt, task));
667    /// ```
668    ///
669    #[macro_export]
670    macro_rules! rumtk_resolve_task {
671        ( $rt:expr, $future:expr ) => {{
672            // Fun tidbit, the expression rumtk_resolve_task!(&rt, rumtk_spawn_task!(&rt, task)), where
673            // rt is the tokio runtime yields async move { { &rt.spawn(task) } }. However, the whole thing
674            // is technically moved into the async closure and captured so things like mutex guards
675            // technically go out of the outer scope. As a result that expression fails to compile even
676            // though the intent is for rumtk_spawn_task to resolve first and its result get moved
677            // into the async closure. To ensure that happens regardless of given expression, we do
678            // a variable assignment below to force the "future" macro expressions to resolve before
679            // moving into the closure. DO NOT REMOVE OR "SIMPLIFY" THE let future = $future LINE!!!
680            let future = $future;
681            $rt.block_on(async move { future.await })
682        }};
683    }
684
685    #[macro_export]
686    macro_rules! rumtk_resolve_task_from_async {
687        ( $rt:expr, $future:expr ) => {{
688            let handle = $rt.spawn_blocking(async move { future.await })
689        }};
690    }
691
692    ///
693    /// This macro creates an async body that calls the async closure and awaits it.
694    ///
695    /// ## Example
696    ///
697    /// ```
698    /// use std::sync::{Arc, RwLock};
699    /// use tokio::sync::RwLock as AsyncRwLock;
700    /// use rumtk_core::strings::RUMString;
701    /// use rumtk_core::threading::threading_manager::{SafeTaskArgs, TaskItems};
702    ///
703    /// pub type SafeTaskArgs2<T> = Arc<RwLock<TaskItems<T>>>;
704    /// let expected = vec![
705    ///     RUMString::from("Hello"),
706    ///     RUMString::from("World!"),
707    ///     RUMString::from("Overcast"),
708    ///     RUMString::from("and"),
709    ///     RUMString::from("Sad"),
710    ///  ];
711    /// let locked_args = AsyncRwLock::new(expected.clone());
712    /// let task_args = SafeTaskArgs::<RUMString>::new(locked_args);
713    ///
714    ///
715    /// ```
716    ///
717    #[macro_export]
718    macro_rules! rumtk_create_task {
719        ( $func:expr ) => {{
720            async move {
721                let f = $func;
722                f().await
723            }
724        }};
725        ( $func:expr, $args:expr ) => {{
726            let f = $func;
727            async move { f(&$args).await }
728        }};
729    }
730
731    ///
732    /// Creates an instance of [SafeTaskArgs] with the arguments passed.
733    ///
734    /// ## Note
735    ///
736    /// All arguments must be of the same type
737    ///
738    #[macro_export]
739    macro_rules! rumtk_create_task_args {
740        ( ) => {{
741            use $crate::threading::threading_manager::{TaskArgs, SafeTaskArgs, TaskItems};
742            use tokio::sync::RwLock;
743            SafeTaskArgs::new(RwLock::new(vec![]))
744        }};
745        ( $($args:expr),+ ) => {{
746            use $crate::threading::threading_manager::{SafeTaskArgs};
747            use tokio::sync::RwLock;
748            SafeTaskArgs::new(RwLock::new(vec![$($args),+]))
749        }};
750    }
751
752    ///
753    /// Convenience macro for packaging the task components and launching the task in one line.
754    ///
755    /// One of the advantages is that you can generate a new `tokio` runtime by specifying the
756    /// number of threads at the end. This is optional. Meaning, we will default to the system's
757    /// number of threads if that value is not specified.
758    ///
759    /// Between the `func` parameter and the optional `threads` parameter, you can specify a
760    /// variable number of arguments to pass to the task. each argument must be of the same type.
761    /// If you wish to pass different arguments with different types, please define an abstract type
762    /// whose underlying structure is a tuple of items and pass that instead.
763    ///
764    /// ## Examples
765    ///
766    /// ### With Default Thread Count
767    /// ```
768    ///     use rumtk_core::{rumtk_exec_task};
769    ///     use rumtk_core::core::RUMResult;
770    ///     use rumtk_core::threading::threading_manager::SafeTaskArgs;
771    ///
772    ///     async fn test(args: &SafeTaskArgs<i32>) -> RUMResult<Vec<i32>> {
773    ///         let mut result = Vec::<i32>::new();
774    ///         for arg in args.read().await.iter() {
775    ///             result.push(*arg);
776    ///         }
777    ///         Ok(result)
778    ///     }
779    ///
780    ///     let result = rumtk_exec_task!(test, vec![5]);
781    ///     assert_eq!(&result.clone().unwrap(), &vec![5], "Results mismatch");
782    ///     assert_ne!(&result.clone().unwrap(), &vec![5, 10], "Results do not mismatch as expected!");
783    /// ```
784    ///
785    /// ### With Custom Thread Count
786    /// ```
787    ///     use rumtk_core::{rumtk_exec_task};
788    ///     use rumtk_core::core::RUMResult;
789    ///     use rumtk_core::threading::threading_manager::SafeTaskArgs;
790    ///
791    ///     async fn test(args: &SafeTaskArgs<i32>) -> RUMResult<Vec<i32>> {
792    ///         let mut result = Vec::<i32>::new();
793    ///         for arg in args.read().await.iter() {
794    ///             result.push(*arg);
795    ///         }
796    ///         Ok(result)
797    ///     }
798    ///
799    ///     let result = rumtk_exec_task!(test, vec![5], 5);
800    ///     assert_eq!(&result.clone().unwrap(), &vec![5], "Results mismatch");
801    ///     assert_ne!(&result.clone().unwrap(), &vec![5, 10], "Results do not mismatch as expected!");
802    /// ```
803    ///
804    /// ### With Async Function Body
805    /// ```
806    ///     use rumtk_core::{rumtk_exec_task};
807    ///     use rumtk_core::core::RUMResult;
808    ///     use rumtk_core::threading::threading_manager::SafeTaskArgs;
809    ///
810    ///     let result = rumtk_exec_task!(
811    ///     async move |args: &SafeTaskArgs<i32>| -> RUMResult<Vec<i32>> {
812    ///         let mut result = Vec::<i32>::new();
813    ///         for arg in args.read().await.iter() {
814    ///             result.push(*arg);
815    ///         }
816    ///         Ok(result)
817    ///     },
818    ///     vec![5]);
819    ///     assert_eq!(&result.clone().unwrap(), &vec![5], "Results mismatch");
820    ///     assert_ne!(&result.clone().unwrap(), &vec![5, 10], "Results do not mismatch as expected!");
821    /// ```
822    ///
823    /// ### With Async Function Body and No Args
824    /// ```
825    ///     use rumtk_core::{rumtk_exec_task};
826    ///     use rumtk_core::core::RUMResult;
827    ///     use rumtk_core::threading::threading_manager::SafeTaskArgs;
828    ///
829    ///     let result = rumtk_exec_task!(
830    ///     async || -> RUMResult<Vec<i32>> {
831    ///         let mut result = Vec::<i32>::new();
832    ///         Ok(result)
833    ///     });
834    ///     let empty = Vec::<i32>::new();
835    ///     assert_eq!(&result.clone().unwrap(), &empty, "Results mismatch");
836    ///     assert_ne!(&result.clone().unwrap(), &vec![5, 10], "Results do not mismatch as expected!");
837    /// ```
838    ///
839    /// ## Equivalent To
840    ///
841    /// ```
842    ///     use rumtk_core::{rumtk_init_threads, rumtk_resolve_task, rumtk_create_task_args, rumtk_create_task, rumtk_spawn_task};
843    ///     use rumtk_core::core::RUMResult;
844    ///     use rumtk_core::threading::threading_manager::SafeTaskArgs;
845    ///
846    ///     async fn test(args: &SafeTaskArgs<i32>) -> RUMResult<Vec<i32>> {
847    ///         let mut result = Vec::<i32>::new();
848    ///         for arg in args.read().await.iter() {
849    ///             result.push(*arg);
850    ///         }
851    ///         Ok(result)
852    ///     }
853    ///
854    ///     let rt = rumtk_init_threads!();
855    ///     let args = rumtk_create_task_args!(1);
856    ///     let task = rumtk_create_task!(test, args);
857    ///     let result = rumtk_resolve_task!(&rt, rumtk_spawn_task!(&rt, task));
858    /// ```
859    ///
860    #[macro_export]
861    macro_rules! rumtk_exec_task {
862        ($func:expr ) => {{
863            use tokio::sync::RwLock;
864            use $crate::{
865                rumtk_create_task, rumtk_create_task_args, rumtk_init_threads, rumtk_resolve_task,
866            };
867            let rt = rumtk_init_threads!();
868            let task = rumtk_create_task!($func);
869            rumtk_resolve_task!(&rt, task)
870        }};
871        ($func:expr, $args:expr ) => {{
872            use tokio::sync::RwLock;
873            use $crate::{
874                rumtk_create_task, rumtk_create_task_args, rumtk_init_threads, rumtk_resolve_task,
875            };
876            let rt = rumtk_init_threads!();
877            let args = SafeTaskArgs::new(RwLock::new($args));
878            let task = rumtk_create_task!($func, args);
879            rumtk_resolve_task!(&rt, task)
880        }};
881        ($func:expr, $args:expr , $threads:expr ) => {{
882            use tokio::sync::RwLock;
883            use $crate::{
884                rumtk_create_task, rumtk_create_task_args, rumtk_init_threads, rumtk_resolve_task,
885            };
886            let rt = rumtk_init_threads!(&$threads);
887            let args = SafeTaskArgs::new(RwLock::new($args));
888            let task = rumtk_create_task!($func, args);
889            rumtk_resolve_task!(&rt, task)
890        }};
891    }
892
893    ///
894    /// Sleep a duration of time in a sync context, so no await can be call on the result.
895    ///
896    /// You can pass any value that can be cast to f32.
897    ///
898    /// The precision is up to nanoseconds and it is depicted by the number of decimal places.
899    ///
900    /// ## Examples
901    ///
902    /// ```
903    ///     use rumtk_core::rumtk_sleep;
904    ///     rumtk_sleep!(1);           // Sleeps for 1 second.
905    ///     rumtk_sleep!(0.001);       // Sleeps for 1 millisecond
906    ///     rumtk_sleep!(0.000001);    // Sleeps for 1 microsecond
907    ///     rumtk_sleep!(0.000000001); // Sleeps for 1 nanosecond
908    /// ```
909    ///
910    #[macro_export]
911    macro_rules! rumtk_sleep {
912        ( $dur:expr) => {{
913            use $crate::threading::threading_functions::sleep;
914            sleep($dur as f32)
915        }};
916    }
917
918    ///
919    /// Sleep for some duration of time in an async context. Meaning, we can be awaited.
920    ///
921    /// You can pass any value that can be cast to f32.
922    ///
923    /// The precision is up to nanoseconds and it is depicted by the number of decimal places.
924    ///
925    /// ## Examples
926    ///
927    /// ```
928    ///     use rumtk_core::{rumtk_async_sleep, rumtk_exec_task};
929    ///     use rumtk_core::core::RUMResult;
930    ///     rumtk_exec_task!( async || -> RUMResult<()> {
931    ///             rumtk_async_sleep!(1).await;           // Sleeps for 1 second.
932    ///             rumtk_async_sleep!(0.001).await;       // Sleeps for 1 millisecond
933    ///             rumtk_async_sleep!(0.000001).await;    // Sleeps for 1 microsecond
934    ///             rumtk_async_sleep!(0.000000001).await; // Sleeps for 1 nanosecond
935    ///             Ok(())
936    ///         }
937    ///     );
938    /// ```
939    ///
940    #[macro_export]
941    macro_rules! rumtk_async_sleep {
942        ( $dur:expr) => {{
943            use $crate::threading::threading_functions::async_sleep;
944            async_sleep($dur as f32)
945        }};
946    }
947
948    ///
949    ///
950    ///
951    #[macro_export]
952    macro_rules! rumtk_new_task_queue {
953        ( $worker_num:expr ) => {{
954            use $crate::threading::threading_manager::TaskManager;
955            TaskManager::new($worker_num);
956        }};
957    }
958}