Search code examples
concurrencycrystal-lang

How can I stop a Fiber?


Let's say we have a Fiber with a long running loop and with the given timeout channel when we receive message we want to stop the fiber and restart it(or do something else). Here is the pseudo code:

# we have a timeout channel
fiber = spawn do 
  # long running task
  # note that I can't pass anything to the function to stop
  Something.run
end

fiber.stop if timeout.receive

Solution

  • There is currently no way to stop a fiber from outside.

    However, in #6450 there is a proposal to add Fiber#cancel which would provide a method to soft terminate a fiber by raising a CancelledException in its execution context the next time it is resumed. This is still an active discussion, describing your use-case there would certainly be a helpful insight.

    A different option would be to hard-kill a fiber by simply removing it from the scheduler. This however would never give it any chance to clean up its resources and is probably not what you want. There is no official API for this yet anyway.