TaskManager

Struct TaskManager 

Source
pub struct TaskManager<R> { /* private fields */ }
Expand description

Manages asynchronous tasks submitted as micro jobs from synchronous code. This type essentially gives the multithreading, asynchronous superpowers to synchronous logic.

§Example Usage

use std::sync::{Arc};
use tokio::sync::RwLock as AsyncRwLock;
use rumtk_core::core::RUMResult;
use rumtk_core::strings::RUMString;
use rumtk_core::threading::threading_manager::{SafeTaskArgs, TaskItems, TaskManager};
use rumtk_core::{rumtk_create_task, };

let expected = vec![
    RUMString::from("Hello"),
    RUMString::from("World!"),
    RUMString::from("Overcast"),
    RUMString::from("and"),
    RUMString::from("Sad"),
 ];

type TestResult = RUMResult<Vec<RUMString>>;
let mut queue: TaskManager<TestResult> = TaskManager::new(&5).unwrap();

let locked_args = AsyncRwLock::new(expected.clone());
let task_args = SafeTaskArgs::<RUMString>::new(locked_args);
let processor = rumtk_create_task!(
    async |args: &SafeTaskArgs<RUMString>| -> TestResult {
        let owned_args = Arc::clone(args);
        let locked_args = owned_args.read().await;
        let mut results = TaskItems::<RUMString>::with_capacity(locked_args.len());

        for arg in locked_args.iter() {
            results.push(RUMString::new(arg));
        }

        Ok(results)
    },
    task_args
);

queue.add_task::<_>(processor);
let results = queue.wait();

let mut result_data = Vec::<RUMString>::with_capacity(5);
for r in results {
    for v in r.unwrap().result.clone().unwrap().iter() {
        for value in v.iter() {
            result_data.push(value.clone());
        }
    }
 }

assert_eq!(result_data, expected, "Results do not match expected!");

Implementations§

Source§

impl<R> TaskManager<R>
where R: Sync + Send + Clone + 'static,

Source

pub fn default() -> RUMResult<TaskManager<R>>

This method creates a [TaskQueue] instance using sensible defaults.

The threads field is computed from the number of cores present in system.

Source

pub fn new(worker_num: &usize) -> RUMResult<TaskManager<R>>

Creates an instance of [ThreadedTaskQueue<T, R>] in the form of [SafeThreadedTaskQueue<T, R>]. Expects you to provide the count of threads to spawn and the microtask queue size allocated by each thread.

This method calls [Self::with_capacity()] for the actual object creation. The main queue capacity is pre-allocated to [DEFAULT_QUEUE_CAPACITY].

Source

pub async fn add_task_async<F>(&mut self, task: F) -> TaskID
where F: Future<Output = R> + Send + Sync + 'static, F::Output: Send + Sized + 'static,

Add a task to the processing queue. The idea is that you can queue a processor function and list of args that will be picked up by one of the threads for processing.

This is the async counterpart

Source

pub fn add_task<F>(&mut self, task: F) -> TaskID
where F: Future<Output = R> + Send + Sync + 'static, F::Output: Send + Sized + 'static,

Source

pub fn wait(&mut self) -> TaskResults<R>

Source

pub fn wait_on_batch(&mut self, tasks: &TaskBatch) -> TaskResults<R>

Source

pub fn wait_on(&mut self, task_id: &TaskID) -> TaskResult<R>

Source

pub async fn wait_on_async(&mut self, task_id: &TaskID) -> TaskResult<R>

This method waits until a queued task with TaskID has been processed from the main queue.

We poll the status of the task every DEFAULT_SLEEP_DURATION ms.

Upon completion,

  1. Return the result (TaskResults).

This operation consumes the task.

§Note:
    Results returned here are not guaranteed to be in the same order as the order in which
    the tasks were queued for work. You will need to pass a type as T that automatically
    tracks its own id or has a way for you to resort results.
Source

pub async fn wait_on_batch_async(&mut self, tasks: &TaskBatch) -> TaskResults<R>

This method waits until a set of queued tasks with TaskID has been processed from the main queue.

We poll the status of the task every DEFAULT_SLEEP_DURATION ms.

Upon completion,

  1. We collect the results generated (if any).
  2. Return the list of results (TaskResults).
§Note:
    Results returned here are not guaranteed to be in the same order as the order in which
    the tasks were queued for work. You will need to pass a type as T that automatically
    tracks its own id or has a way for you to resort results.
Source

pub async fn wait_async(&mut self) -> TaskResults<R>

This method waits until all queued tasks have been processed from the main queue.

We poll the status of the main queue every DEFAULT_SLEEP_DURATION ms.

Upon completion,

  1. We collect the results generated (if any).
  2. We reset the main task and result internal queue states.
  3. Return the list of results (TaskResults).

This operation consumes all the tasks.

§Note:
    Results returned here are not guaranteed to be in the same order as the order in which
    the tasks were queued for work. You will need to pass a type as T that automatically
    tracks its own id or has a way for you to resort results.
Source

pub fn is_all_completed(&self) -> bool

Check if all work has been completed from the task queue.

§Examples
§Sync Usage
 use rumtk_core::threading::threading_manager::TaskManager;

 let manager = TaskManager::<usize>::new(&4).unwrap();

 let all_done = manager.is_all_completed();

 assert_eq!(all_done, true, "Empty TaskManager reports tasks are not completed!");
Source

pub async fn is_all_completed_async(&self) -> bool

Trait Implementations§

Source§

impl<R: Clone> Clone for TaskManager<R>

Source§

fn clone(&self) -> TaskManager<R>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<R: Debug> Debug for TaskManager<R>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<R: Default> Default for TaskManager<R>

Source§

fn default() -> TaskManager<R>

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<R> Freeze for TaskManager<R>

§

impl<R> !RefUnwindSafe for TaskManager<R>

§

impl<R> Send for TaskManager<R>
where R: Send + Sync,

§

impl<R> Sync for TaskManager<R>
where R: Send + Sync,

§

impl<R> Unpin for TaskManager<R>

§

impl<R> !UnwindSafe for TaskManager<R>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> Ungil for T
where T: Send,