[][src]Struct glommio::Task

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

A spawned future.

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::make_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::make_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::{LocalExecutorBuilder, Local};

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>, QueueNotFoundError> 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::{LocalExecutor, Task, Shares};

let local_ex = LocalExecutor::make_default();
let handle = local_ex.create_task_queue(Shares::default(), glommio::Latency::NotImportant, "test_queue");

local_ex.spawn_into(async {
    let task = Task::local(async { 1 + 2 });
    assert_eq!(task.await, 3);
}, handle).expect("failed to spawn task");

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::make_default();

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

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

Notable traits for JoinHandle<R, T>

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

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

Examples

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

let ex = LocalExecutor::make_default();

ex.spawn(async {
    loop {
        println!("I'm a background task looping forever.");
        Task::<()>::later().await;
    }
})
.detach();

ex.run(async { 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

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::{LocalExecutor, Local, Latency, 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, QueueNotFoundError>
[src]

Returns a Result with its Ok value wrapping a TaskQueueStats or QueueNotFoundError if there is no task queue with this handle

Examples

use glommio::{Local, Latency, 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::{Local, Latency, 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 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 glommio::{LocalExecutor, Task};
use futures_lite::future;

let ex = LocalExecutor::make_default();

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

ex.run(async {
    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> where
    T: Send

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> Same<T> for T[src]

type Output = T

Should always be Self

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
[src]

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.