task parking / unparking
andrewbanchich opened this issue · 5 comments
I'd love the ability to pause / resume Tasks.
I'm in agreement with, @andrewbanchich
We could likely model this similar to the std::thread
"parking" APIs, but with the benefit that unlike Thread
futures permit external parking as well. For a counterpart to crossbeam's Parker/Unparker
I've been experimenting with this here. Luckily this is executor-agnostic, though it's not yet implemented directly in terms of atomics and may be subject to races. But at least the shape of the API seems alright.
Proposed API
impl Task {
/// Stop execution of the `Task` until `unpark` is called.
///
/// If the task was already parked this has no effect.
// NOTE: this method does not exist on `std::thread::Thread`
// NOTE: should this be an `async fn`?
pub fn park(&self);
/// Resume execution of the `Task` if it was parked.
///
/// If the task was not parked this has no effect.
pub fn unpark(&self);
}
/// Suspend execution of the current task.
// NOTE: we're not always guaranteed to be in a task. What should happen if we detect we aren't?
pub async fn park();
I feel as the proposed fn is a. Necessity. While I currently have nothing further to contribute with respect to "suggestions" regarding the implementation(s) of the API struct--I am very interested in the proposed-format and I will definitely spend more time with it to evaluate any direct/indirect- pros and cons and then will follow back up with results. The example here is great I'm fired up about the notion personally. Thank you, @yoshuawuyts!
REF: "test parking/unpacking #13"
I feel like this shouldn't be a part of this crate. You could model a "pausable future" using something like this:
struct PausableFuture<F> {
fut: F,
paused: Arc<AtomicBool>,
}
struct PauseHandle {
paused: Arc<AtomicBool>,
}
// new() takes F, creates paused, clones it, then returns both of the above types
impl PauseHandle {
fn pause(&self) {
self.paused.store(true);
}
fn unpause(&self) {
self.paused.store(false);
}
}
impl Future for PausedFuture<F> {
fn poll() {
if self.paused.load() {
Poll::Pending
} else {
self.fut.poll()
}
}
}
You'd also need to deal with wakers and such, but this can easily be done without this crate.
I've recently been working on a new model for tasks. Instead of "a task is an async thread" it's now: "a task is a parallelizable future". And all concurrency operations available on Task
should be available on Future
as well.
I've successfully authored a FutureExt::park method which implements these semantics. And I think it's probably best if we evolve that in a crate other than async-task
.