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