Struct glommio::Task[][src]

#[must_use = "tasks get canceled when dropped, use `.detach()` to run them in the background"]
pub struct Task<T>(_);

A spawned future that can be detached

Because these tasks can be detached, the futures they execute must be 'static. Usually the pattern to make sure something is static is to use Rc<RefCell<T>> or Rc<Cell<T>> and clone it, but that has a cost. If that cost is deemed unacceptable, and you are able to have a well-defined lifetime, and understand its safety considerations, you can use a ScopedTask

Tasks are also futures themselves and yield the output of the spawned future.

When a task is dropped, its gets canceled and won’t be polled again. To cancel a task a bit more gracefully and wait until it stops running, use the cancel() method.

Tasks that panic get immediately canceled. Awaiting a canceled task also causes a panic.

Examples

use glommio::{LocalExecutor, Task};

let ex = LocalExecutor::default();

ex.run(async {
    let task = Task::local(async {
        println!("Hello from a task!");
        1 + 2
    });

    assert_eq!(task.await, 3);
});

Implementations

impl<T> Task<T>[src]

pub fn local(future: impl Future<Output = T> + 'static) -> Task<T>

Notable traits for Task<T>

impl<T> Future for Task<T> type Output = T;
where
    T: 'static, 
[src]

Spawns a task onto the current single-threaded executor.

If called from a LocalExecutor, the task is spawned on it.

Otherwise, this method panics.

Examples

use glommio::{LocalExecutor, Task};

let local_ex = LocalExecutor::default();

local_ex.run(async {
    let task = Task::local(async { 1 + 2 });
    assert_eq!(task.await, 3);
});

pub async fn later()[src]

Unconditionally yields the current task, moving it back to the end of its queue. It is not possible to yield futures that are not spawn’d, as they don’t have a task associated with them.

pub fn need_preempt() -> bool[src]

checks if this task has ran for too long and need to be preempted. This is useful for situations where we can’t call .await, for instance, if a RefMut is held. If this tests true, then the user is responsible for making any preparations necessary for calling .await and doing it themselves.

Examples

use glommio::{Local, LocalExecutorBuilder};

let ex = LocalExecutorBuilder::new()
    .spawn(|| async {
        loop {
            if Local::need_preempt() {
                break;
            }
        }
    })
    .unwrap();

ex.join().unwrap();

pub async fn yield_if_needed()[src]

Conditionally yields the current task, moving it back to the end of its queue, if the task has run for too long

pub fn local_into(
    future: impl Future<Output = T> + 'static,
    handle: TaskQueueHandle
) -> Result<Task<T>, ()> where
    T: 'static, 
[src]

Spawns a task onto the current single-threaded executor, in a particular task queue

If called from a LocalExecutor, the task is spawned on it.

Otherwise, this method panics.

Examples

use glommio::{Local, LocalExecutor, Shares, Task};

let local_ex = LocalExecutor::default();
local_ex.run(async {
    let handle = Local::create_task_queue(
        Shares::default(),
        glommio::Latency::NotImportant,
        "test_queue",
    );
    let task =
        Task::<usize>::local_into(async { 1 + 2 }, handle).expect("failed to spawn task");
    assert_eq!(task.await, 3);
})

pub fn id() -> usize where
    T: 'static, 
[src]

Returns the id of the current executor

If called from a LocalExecutor, returns the id of the executor.

Otherwise, this method panics.

Examples

use glommio::{LocalExecutor, Task};

let local_ex = LocalExecutor::default();

local_ex.run(async {
    println!("my ID: {}", Task::<()>::id());
});

pub fn detach(self) -> JoinHandle<T>

Notable traits for JoinHandle<R>

impl<R> Future for JoinHandle<R> type Output = Option<R>;
[src]

Detaches the task to let it keep running in the background.

Examples

use futures_lite::future;
use glommio::{timer::Timer, Local, LocalExecutor};

let ex = LocalExecutor::default();
ex.run(async {
    Local::local(async {
        loop {
            println!("I'm a background task looping forever.");
            Local::later().await;
        }
    })
    .detach();
    Timer::new(std::time::Duration::from_micros(100)).await;
})

pub fn create_task_queue(
    shares: Shares,
    latency: Latency,
    name: &str
) -> TaskQueueHandle
[src]

Creates a new task queue, with a given latency hint and the provided name

Each task queue is scheduled based on the Shares and Latency system, and tasks within a queue will be scheduled in serial.

Returns an opaque handle that can later be used to launch tasks into that queue with local_into.

Examples

use glommio::{Latency, Local, LocalExecutor, Shares};
use std::time::Duration;

let local_ex = LocalExecutor::default();
local_ex.run(async move {
    let task_queue = Local::create_task_queue(
        Shares::default(),
        Latency::Matters(Duration::from_secs(1)),
        "my_tq",
    );
    let task = Local::local_into(
        async {
            println!("Hello world");
        },
        task_queue,
    )
    .expect("failed to spawn task");
});

pub fn current_task_queue() -> TaskQueueHandle[src]

Returns the TaskQueueHandle that represents the TaskQueue currently running. This can be passed directly into Task::local_into. This must be run from a task that was generated through Task::local or Task::local_into

Examples

use glommio::{Latency, Local, LocalExecutor, LocalExecutorBuilder, Shares};

let ex = LocalExecutorBuilder::new()
    .spawn(|| async move {
        let original_tq = Local::current_task_queue();
        let new_tq = Local::create_task_queue(Shares::default(), Latency::NotImportant, "test");

        let task = Local::local_into(
            async move {
                Local::local_into(
                    async move {
                        assert_eq!(Local::current_task_queue(), original_tq);
                    },
                    original_tq,
                )
                .unwrap();
            },
            new_tq,
        )
        .unwrap();
        task.await;
    })
    .unwrap();

ex.join().unwrap();

pub fn task_queue_stats(handle: TaskQueueHandle) -> Result<TaskQueueStats, ()>[src]

Returns a Result with its Ok value wrapping a TaskQueueStats or a GlommioError of type [QueueErrorKind] if there is no task queue with this handle

Examples

use glommio::{Latency, Local, LocalExecutorBuilder, Shares};

let ex = LocalExecutorBuilder::new()
    .spawn(|| async move {
        let new_tq = Local::create_task_queue(Shares::default(), Latency::NotImportant, "test");
        println!(
            "Stats for test: {:?}",
            Local::task_queue_stats(new_tq).unwrap()
        );
    })
    .unwrap();

ex.join().unwrap();

pub fn all_task_queue_stats<V>(output: V) -> V where
    V: Extend<TaskQueueStats>, 
[src]

Returns a collection of TaskQueueStats with information about all task queues in the system

The collection can be anything that implements Extend and it is initially passed by the user so they can control how allocations are done.

Examples

use glommio::{Latency, Local, LocalExecutorBuilder, Shares};

let ex = LocalExecutorBuilder::new()
    .spawn(|| async move {
        let new_tq = Local::create_task_queue(Shares::default(), Latency::NotImportant, "test");
        let v = Vec::new();
        println!("Stats for all queues: {:?}", Local::all_task_queue_stats(v));
    })
    .unwrap();

ex.join().unwrap();

pub fn executor_stats() -> ExecutorStats[src]

Returns a ExecutorStats struct with information about this Executor

Examples:

use glommio::{Local, LocalExecutorBuilder};

let ex = LocalExecutorBuilder::new()
    .spawn(|| async move {
        println!("Stats for executor: {:?}", Local::executor_stats());
    })
    .unwrap();

ex.join().unwrap();

pub fn io_stats() -> IoStats[src]

Returns an IoStats struct with information about IO performed by this executor’s reactor

Examples:

use glommio::{Local, LocalExecutorBuilder};

let ex = LocalExecutorBuilder::new()
    .spawn(|| async move {
        println!("Stats for executor: {:?}", Local::io_stats());
    })
    .unwrap();

ex.join().unwrap();

pub fn task_queue_io_stats(handle: TaskQueueHandle) -> Result<IoStats, ()>[src]

Returns an IoStats struct with information about IO performed from the provided TaskQueue by this executor’s reactor

Examples:

use glommio::{Latency, Local, LocalExecutorBuilder, Shares};

let ex = LocalExecutorBuilder::new()
    .spawn(|| async move {
        let new_tq = Local::create_task_queue(Shares::default(), Latency::NotImportant, "test");
        println!(
            "Stats for executor: {:?}",
            Local::task_queue_io_stats(new_tq)
        );
    })
    .unwrap();

ex.join().unwrap();

pub async fn cancel(self) -> Option<T>[src]

Cancels the task and waits for it to stop running.

Returns the task’s output if it was completed just before it got canceled, or None if it didn’t complete.

While it’s possible to simply drop the Task to cancel it, this is a cleaner way of canceling because it also waits for the task to stop running.

Examples

use futures_lite::future;
use glommio::{Local, LocalExecutor};

let ex = LocalExecutor::default();

ex.run(async {
    let task = Local::local(async {
        loop {
            println!("Even though I'm in an infinite loop, you can still cancel me!");
            future::yield_now().await;
        }
    });

    task.cancel().await;
});

Trait Implementations

impl<T: Debug> Debug for Task<T>[src]

impl<T> Future for Task<T>[src]

type Output = T

The type of value produced on completion.

Auto Trait Implementations

impl<T> RefUnwindSafe for Task<T> where
    T: RefUnwindSafe

impl<T> !Send for Task<T>

impl<T> !Sync for Task<T>

impl<T> Unpin for Task<T>

impl<T> UnwindSafe for Task<T> where
    T: UnwindSafe

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<F> FutureExt for F where
    F: Future + ?Sized
[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<F> IntoFuture for F where
    F: Future
[src]

type Output = <F as Future>::Output

🔬 This is a nightly-only experimental API. (into_future)

The output that the future will produce on completion.

type Future = F

🔬 This is a nightly-only experimental API. (into_future)

Which kind of future are we turning this into?

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<F, T, E> TryFuture for F where
    F: Future<Output = Result<T, E>> + ?Sized

type Ok = T

The type of successful values yielded by this future

type Error = E

The type of failures yielded by this future

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.