Skip to content

Implement cancellation in context & future<T> #37

Closed
1 of 1 issue completed
Closed

Description

@kammce

Safe by default means that cancellation only occurs if the context is in an acceptable state to be cancelled. For example, blocked by I/O and external are probably unacceptable to cancel because IO may be writing to a resource currently held by the coroutine frame. Destroying the frame but allowing that coroutine stack memory to be reused by other coroutine frames would be disastrous. Blocked by external would also be a lifetime violation because some external coroutine scheduler/executor is expected to resume our coroutine and if they do so and our frame has been destroyed, we'd get UB. Being blocked by nothing is the perfect time to be cancelled. Being blocked by time and sync are also acceptable to be cancelled.

Calling cancel() would cancel if the state is cancellable or simply return. To be assured that the cancellation went through, the is_cancelled() API can be called. We could also provide a sync_cancel(). A better name combo would be try_cancel(), which attempts to cancel the operation, and cancel(), which performs a synchronous operation of waiting until the coroutine is cancelled before returning.

Activity

  1. kammce commented on Jan 14, 2026

    @kammce
    MemberAuthor

    Thinking it over, I like the combo of try_cancel() and is_cancelled(). I don't see a reason to provide a hard CPU bound polling cancel for a future as the time that the operation may be blocked for it unknown. Making it clear with the words "try" is important to convey to users that a cancellation may not be possible.

    This goes for context as well. The only time cancellation will block is in the destruction of a future or context. In those scenarios, the users must pay for cancellation on their threads for lifetime safety reasons.

  2. changed the title [-]Consider if `future::cancel` should be safe by default[/-] [+]Migrate to `future::try_cancel`[/+] on Jan 15, 2026
  3. changed the title [-]Migrate to `future::try_cancel`[/-] [+]Implement cancellation in context & future<T>[/+] on Jan 15, 2026
  4. kammce commented on Jan 17, 2026

    @kammce
    MemberAuthor

    Resolved in #56

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions