Function async_task::spawn_local

source ·
pub fn spawn_local<F, S>(future: F, schedule: S) -> (Runnable, Task<F::Output>)
where F: Future + 'static, F::Output: 'static, S: Fn(Runnable) + Send + Sync + 'static,
Expand description

Creates a new thread-local task.

This function is same as spawn(), except it does not require Send on future. If the Runnable is used or dropped on another thread, a panic will occur.

This function is only available when the std feature for this crate is enabled.

§Examples

use async_task::Runnable;
use flume::{Receiver, Sender};
use std::rc::Rc;

thread_local! {
    // A queue that holds scheduled tasks.
    static QUEUE: (Sender<Runnable>, Receiver<Runnable>) = flume::unbounded();
}

// Make a non-Send future.
let msg: Rc<str> = "Hello, world!".into();
let future = async move {
    println!("{}", msg);
};

// A function that schedules the task when it gets woken up.
let s = QUEUE.with(|(s, _)| s.clone());
let schedule = move |runnable| s.send(runnable).unwrap();

// Create a task with the future and the schedule function.
let (runnable, task) = async_task::spawn_local(future, schedule);