pub struct Task<T>(/* private fields */);
Expand description
A spawned future that can be detached
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
let task = glommio::spawn_local(async {
println!("Hello from a task!");
1 + 2
});
assert_eq!(task.await, 3);
Note that there is no guarantee of ordering when reasoning about when a task runs, as that is an implementation detail.
In particular, acquiring a borrow and holding across a task spawning may sometimes work but panic depending on scheduling decisions, so it is still illegal.
let example = Rc::new(RefCell::new(0));
let exclone = example.clone();
let mut ex_mut = example.borrow_mut();
*ex_mut = 1;
let task = glommio::spawn_local(async move {
let ex = exclone.borrow();
println!("Current value: {ex}");
});
// This is fine if `task` executes after the current task, but will panic if
// preempts the current task and executes first. This is therefore invalid.
*ex_mut = 2;
drop(ex_mut);
task.await;
Implementations§
source§impl<T> Task<T>
impl<T> Task<T>
sourcepub fn detach(self) -> JoinHandle<T> ⓘ
pub fn detach(self) -> JoinHandle<T> ⓘ
Detaches the task to let it keep running in the background.
§Examples
use futures_lite::future;
use glommio::{timer::Timer, LocalExecutor};
let ex = LocalExecutor::default();
ex.run(async {
glommio::spawn_local(async {
loop {
println!("I'm a background task looping forever.");
glommio::executor().yield_task_queue_now().await;
}
})
.detach();
Timer::new(std::time::Duration::from_micros(100)).await;
})
sourcepub async fn cancel(self) -> Option<T>
pub async fn cancel(self) -> Option<T>
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::LocalExecutor;
let ex = LocalExecutor::default();
ex.run(async {
let task = glommio::spawn_local(async {
loop {
println!("Even though I'm in an infinite loop, you can still cancel me!");
future::yield_now().await;
}
});
task.cancel().await;
});