pub struct Executor<P: Pool = DefaultPool>(_);
Expand description
Pasts’ executor.
Run a Future
It’s relatively simple to block on a future, and run it to completion:
use pasts::Executor;
fn main() {
Executor::default().block_on(async {
println!("Hello from a future!");
});
}
Spawn a Future
You may spawn tasks on an Executor
. Only once all tasks have completed,
can block_on()
return.
use core::time::Duration;
use pasts::Executor;
async fn sleep(seconds: f64) {
async_std::task::sleep(Duration::from_secs_f64(seconds)).await;
}
fn main() {
let executor = Executor::default();
// Spawn before blocking puts the task on a queue.
executor.spawn_boxed(async {
sleep(3.0).await;
println!("3 seconds");
});
// Calling `block_on()` starting executing queued tasks.
executor.clone().block_on(async move {
// Spawn tasks (without being queued)
executor.spawn_boxed(async {
sleep(1.0).await;
println!("1 second");
});
executor.spawn_boxed(async {
sleep(2.0).await;
println!("2 seconds");
});
// Finish this task before spawned tasks will complete.
sleep(0.5).await;
println!("½ second");
});
}
Recursive block_on()
One cool feature about the pasts executor is that you can run it from within the context of another:
use pasts::Executor;
fn main() {
Executor::default().block_on(async {
Executor::default().block_on(async {
println!("Hello from the future running on the inner executor!");
});
println!("Hello from the future running on the outer executor!");
});
}
Or even resume the executor from within it’s own context:
use pasts::Executor;
fn main() {
let executor = Executor::default();
executor.clone().block_on(async move {
println!("Hello from a future!");
executor.block_on(async {
println!("Resuming execution from within the executor context!");
});
});
}
Implementations§
source§impl<P: Pool> Executor<P>
impl<P: Pool> Executor<P>
sourcepub fn new(pool: P) -> Self
pub fn new(pool: P) -> Self
Create a new executor that can only spawn tasks from the current thread.
Custom executors can be built by implementing Pool
.
sourcepub fn block_on(self, f: impl Future<Output = ()> + 'static)
pub fn block_on(self, f: impl Future<Output = ()> + 'static)
Block on a future and return it’s result.
Platform-Specific Behavior
When building with feature web
, spawns task and returns
immediately instead of blocking.
source§impl<P: Pool> Executor<P>
impl<P: Pool> Executor<P>
sourcepub fn spawn_notify(&self, n: LocalBoxNotify<'static>)
pub fn spawn_notify(&self, n: LocalBoxNotify<'static>)
Spawn a LocalBoxNotify
on this executor.
Execution of the LocalBoxNotify
will halt after the first poll that
returns Ready
.
sourcepub fn spawn_boxed(&self, f: impl Future<Output = ()> + 'static)
pub fn spawn_boxed(&self, f: impl Future<Output = ()> + 'static)
Box and spawn a future on this executor.