Project

General

Profile

Feature #17325

Updated by nevans (Nicholas Evans) about 4 years ago

 
 Calling `Fiber#cancel` will force a fiber to return, skipping This skips rescue and catch blocks but running runs all ensure blocks. It behaves can be run on any living fiber, and propagates cancellation to child (resumed) fibers. 

 Basically, I want it to behave as if a you called `break` or `return` were used to jump from all the last suspension point way to the top frame of the fiber. Control will fiber from wherever it is.. Exceptions might be transferred too heavy-weight, can't (and shouldn't) be sent to the canceled fiber so it can run its ensure blocks. 

 ## Propagation from resuming to resumed fibers 

 Any non-root living fiber fibers, and can be canceled and cancellation will propagate to child (resumed) fibers. In this way, a suspended task caught. This can also be canceled even if emulated via `catch/throw` with an anonymous `Object.new`, but that adds an extra stack frame, and implementing it is reliably requires interception of `Fiber.yield`, e.g. adding a `Fiber.throw` (analogous to `Fiber.raise`) which also shouldn't be sent to resuming into an enumerator, and fibers. 

 I tried to match the enumerator will be canceled as well. Transfer of control should match #17221's *(much improved)* new _(much improved!)_ transfer/resume semantics. After switch semantics with cancel propagation. When the cancellation propagates all the way to the bottom of the fiber resume stack, the last fiber in the chain will then be resumed. Resuming fibers will not run until they are yielded back into. 

 ## Suspension of canceled fibers 

 Canceled fibers can still transfer control with `resume`, `yield`, If called multiple times, each `cancel` will propagate cancellation and `transfer`, which may be necessary in order to release resources from `ensure` blocks. For simplicity, subsequent cancels will behave similarly to calling as if `break` or `return` inside an `ensure` block, and the last cancellation reason will overwrite earlier reasons. 

 ## Alternatives 

 `Fiber#raise` could be used, but: 
 * Exceptions are bigger and slower than `break`. 
 * `#raise` can't (and shouldn't) be sent to resuming fibers. (It can't propagate.) 
 * Exceptions can be caught. This might be desirable, but that should be at the discretion of the calling fiber. 

 Catch/Throw could be used (with an anonymous `Object.new`), but: 
 * `catch` adds an extra stack frame. 
 * It would need to add `Fiber#throw` (or wrap/intercept `Fiber.yield`). 
 * A hypothetical `Fiber#throw` should probably only be allowed on yielding fibers (like `Fiber#resume`). (It wouldn't propagate.) was called. 

 Implementation:    https://github.com/ruby/ruby/pull/3766

Back