4

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
Oguz Bilgic
  • 3,392
  • 5
  • 36
  • 59
  • The traditional way is to set some kind of "stop" boolean flag :) – rogerdpack Dec 17 '18 at 22:43
  • Just updated the question, I don't have a way to pass a variable to the function to check with every loop – Oguz Bilgic Dec 17 '18 at 23:10
  • 1
    Yeah, typically I'd says "add something to run to make it interruptible" (or have it key off something internally...) gl! – rogerdpack Dec 18 '18 at 02:36
  • > I don't have a way to pass a variable to the function to check with every loop You do: pass it a channel which you try to receive from for every iteration. – Jonne Haß Dec 18 '18 at 08:18
  • 1
    `Something.run` isn't my code in this case – Oguz Bilgic Dec 18 '18 at 11:14
  • 1
    I think there's no help then - there is no way to stop a native function that doesn't want to be stopped short of killing the entire process, whether we're talking about Crystal function that doesn't yield, or a function linked from a library written in C. – Amadan Dec 19 '18 at 09:12
  • In general "hard killing" (your code or someone else's) is problematic, since it can hard kill in the heart of finally blocks, etc. figuring out a way to poll and gracefully shut down is far easier and introduces fewer bugs. GL! – rogerdpack Dec 19 '18 at 19:10

1 Answers1

2

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.

Johannes Müller
  • 5,581
  • 1
  • 11
  • 25