Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature Request: Add AbortHandle::is_aborted() #2709

Closed
ZhennanWu opened this issue Feb 16, 2023 · 1 comment · Fixed by #2710
Closed

Feature Request: Add AbortHandle::is_aborted() #2709

ZhennanWu opened this issue Feb 16, 2023 · 1 comment · Fixed by #2710

Comments

@ZhennanWu
Copy link
Contributor

ZhennanWu commented Feb 16, 2023

Currently there is already a public Abortable::is_aborted() method, and there seems no obstacle in adding a AbortHandle::is_aborted()

Motivation

Sometimes Abortable needs to be accompanied by cooperative cancellation mechanism such as a atomic boolean flag. Rather than using another repetitive atomic variable, the AbortInner already hosts such atomic variable and the AbortHandle seems to be a good way to expose it.

Here is a hypothetical scenario where Abortable needs to be accompanied by cooperative cancellation mechanism. Suppose we have a blocking Mutex protecting a very tiny shared state, and we wish to stop another task from modifying it by calling its AbortHandle

// Aborter
// ...
let (new_abort_handle, new_abort_reg) = AbortHandle::new_pair();
let cooperative_flag = Asc::new(AtomicBool::new(false)); // new_abort_handle.clone();
{
    let mut guard = mutex.lock();
    // Take out the old task's handle
    let old_abort_handle = std::mem::replace(guard.abort_handle, new_abort_handle);
    old_abort_handle.abort();
    // A modification to the cooperative flag is needed here
    drop(guard);
}
// Spawn a new task using the new handle
tokio::spawn(Abortable::new(some_async_function(args, cooperative_flag), new_abort_reg);
// We wish no modifications to the shared state from the old task from here on

// Abortee
let mut guard = mutex.lock();
// A cooperative checking is needed here
write_into_shared_state(guard.state);
drop(guard);

Since we used a blocking Mutex to protect our state (which is warranted in an async scenario) , it is very likely that our target Future is blocked on the mutex call when the AbortHandle::abort() was called. To solve this issue we would need a cooperative checking in our code. Exposing AbortHandle::is_aborted() would save the user from another atomic boolean flag.

@taiki-e
Copy link
Member

taiki-e commented Feb 17, 2023

I would accept a PR to add this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants