socketry / async

An awesome asynchronous event-driven reactor for Ruby.
MIT License
2.1k stars 86 forks source link

Is there a way to unschedule a Fiber? Or stop it from inside? #104

Closed jsaak closed 3 years ago

jsaak commented 3 years ago

Is there a way to unschedule a Fiber? Or stop it from inside? I have not found a way to do it. I try to use only the ruby 3 interface, to be portable.

I am writing an MQTT client and my program looks like this:

Fiber.schedule do
  loop do
    sleep 30
    do_something
  end
end

Fiber.schedule do
  loop do
    recv_bytes()
    do_something
    recv_bytes()
    do_something
    recv_bytes()
  end
end

The program blocks in one of the recv_bytes() functions. If the TCP connection is broken, then i get back an empty string from recv(), and in that case I want to exit the second Fiber. If possible inside the recv_bytes() function so i do not have to check for disconnection every time I call it. I am looking something between exit and return. (I could throw an exception, but that is not very nice)

And also want to stop the sleeping Fiber, without killing the Reactor. Is this possible?

ioquatix commented 3 years ago

Yes, you can use Task#stop.

jsaak commented 3 years ago

Can you please add a function to the ruby specification? Task is an async class, and this belongs one level higher, I think.

ioquatix commented 3 years ago

You can use Fiber#raise. Sorry, I didn't read your original issue clearly, and just assumed since it was on the async repo, that it was related to the async interfaces.

ioquatix commented 3 years ago

It would be great if you have time to try out Fiber#raise to see if it meets your needs, and I think we should have extended testing in Async to ensure it's compatible.