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


Here is some code to highlight the question a bit:

class Game
  property game_close = false

  def initialize
    spawn mob_ai

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

games = Hash(String, Game).new

games["1"] = Game.new

sleep 0.5

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

puts "Game 1 deleted"


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



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.