What happens to lingering fibers? And what is the proper way to close them?

#1

Here is some code to highlight the question a bit:

class Game
  property game_close = false

  def initialize
    spawn mob_ai
  end

  def mob_ai
    loop do
      break if game_close
      puts "mob ai running"
      sleep 1
    end
  end
end

games = Hash(String, Game).new

games["1"] = Game.new

sleep 0.5

games["1"].game_close = true
games.delete "1"

puts "Game 1 deleted"

sleep

Is doing break if game_close the proper/correct way? I was thinking the fiber would be closed automatically, since it’s deleted from the games hash (no references to it?). Am not entirely sure

Example, if you comment out games["1"].game_close = true, the fiber’s loop will still be running

0 Likes

#2

Fibers aren’t garbage collected until their block exists, because they are still referenced from Fiber.@@fibers at least. There is not way to kill/cancel/stop a fiber in a non-leaking way. You have to implement some form of a loop break and its signalling mechanism yourself.

Relying on a class property is fine at the moment, because there is no parallel execution, but will be a race condition in the future.

2 Likes