smol-rs/async-task

When does schedule called?

Closed this issue · 4 comments

I thought it is called when waker is waked.

If schedule is !Send+!Sync, what will happen if the waker is waked in other threads?

schedule is called when the Waker is waked. It is only not Send + Sync for spawn_unchecked, which is unsafe and stipulates that the Waker not be waked on other threads.

Please point out if I'm wrong. I wrote a program like this:

use async_task::Runnable;
use send_wrapper::SendWrapper;
use std::{cell::RefCell, collections::VecDeque, future::poll_fn, rc::Rc, task::Poll};

fn main() {
    let runnables = Rc::new(RefCell::new(VecDeque::<Runnable>::new()));

    let schedule = {
        let runnables = SendWrapper::new(runnables.clone());
        move |r| runnables.borrow_mut().push_back(r)
    };

    let (runnable, task) = async_task::spawn_local(
        poll_fn(|cx| {
            cx.waker().wake_by_ref();
            Poll::<()>::Pending
        }),
        schedule,
    );
    let t = std::thread::spawn(move || smol::block_on(task));
    runnable.schedule();
    loop {
        let next_task = runnables.borrow_mut().pop_front();
        if let Some(r) = next_task {
            r.run();
        } else {
            break;
        }
    }
    t.join().unwrap();
}

It spawns a async block and waits the task in another thread. The schedule will panic if it's called in other threads. However, this program just blocks and never panics nor exits. Why?

The waker from the task on the main thread isn't being sent to the spawned thread. The waker from the block_on on the spawned thread is being sent to the main thread. The reason why the thread stops is because it's waiting on task forever. The loop breaks out before the task can be scheduled again.

Thank you! Now the problem is solved.