lampepfl / gears

A strawman for a low-level async library in Scala 3.
https://lampepfl.github.io/gears/
Apache License 2.0
257 stars 26 forks source link

Cancellation changes and drop extreneous sources #13

Closed odersky closed 11 months ago

odersky commented 1 year ago
  1. Rename CancellationGroup to CompletionGroup

  2. Also, add a way to install completion handlers that are called when a member of a completion group completes. This allows us to define supervisors for coroutines or actors. Note that, unlike for futures we sometimes do not want to wait for termination of a coroutine (or actor) in a specific val. Instead, the coroutine could be terminated when the enclosing completion group completes (i.e. gets cancelled). But we still want to handle abnormal early termination of the coroutine somehow. Completion handlers are the solution to this. A handler can be installed to be valid in a scope. Then, if any cancellable objects terminate, the handler is called.

  3. Move sources that have to do with general suspension handling to a dotty test directory.

diesalbla commented 1 year ago

These changes allow for cancellation of a group upon a call to await for a result. However, in conversation with @jackcviers, we noticed that this can be further improved to support Cooperative Cancellation. To do so, we need the Async capability to expose such functions as checkCancellation() and pause(), so that the programmer may use them inside the fiber code.

The pause function should unconditionally suspend the current function, and it would prompt the scheduler to yield the current thread and reschedule the current function.

A call to checkCancellation() should do two things: 1) check if the CompletionGroup has been cancelled; and 2) suspend the calling function and yield the thread back to the scheduler. The reason for 2) is that, at the time the fiber calls to check the cancellation, there could be any timeouts in the system already expired, which would have the consequence of cancelling the current fiber, but which the system has not yet executed. Yielding from the current fiber to check cancellation allows the scheduler to issue a "last call" for pending cancel signals, specially from any timeouts in the queue.

Cooperative Cancellation, as discussed in #12, is a basic block for concurrency libraries:

natsukagami commented 11 months ago

Closing as it's already in tree