However, I don’t think it would be a good idea to incorporate an implicit cleanup mechanic into fibers. That would a great deal of complexity for the runtime has to keep track of fibers and figure out in which order to unroll them.
And then the ensure handlers could be doing really anything like starting running something new, while we’re actually supposed to be on the exit path.
No, exit should immediately terminate the process, not run any ensure hooks or whatever. If you want to exit, you should get an exit, not a “rewind the stack(s)”.
Note that this is actually not special with fibers, you get the same behaviour with only a single main fiber:
begin
puts "foo"
exit
ensure
puts "ensure" # never gets printed
end
A fiber is just a very basic concurrency primitive. The path forward is to provide higher-level concurrency mechanisms which can keep track of a fiber’s lifetime, ensure all pieces of work are complete and if necessary, can trigger a graceful stack rewind if a fiber needs to be cancelled.
See [RFC] Structured Concurrency · Issue #6468 · crystal-lang/crystal · GitHub for this.