Fiber.wakeup advice


#1

Hello, I would like to ask you about the following hack:

def wakeup(ev : Crystal::Event)
  timeout = 0.seconds
  zero_timeout = LibC::Timeval.new(
    tv_sec: timeout.total_seconds.to_i,
    tv_usec: timeout.nanoseconds / 1_000
  )
  LibEvent2.event_add ev.@event, pointerof(zero_timeout)
end

def wakeup(ev : Nil)
end

fib = spawn { sleep 1; p fiber: Time.now }

p start: Time.now
sleep 0.1
p wakeup: Time.now

wakeup fib.@resume_event

sleep 2
p fin: Time.now

It works, however I’d like your opinion on two things:

  1. Is it okay in general to do this?
  2. Isn’t it worth adding to Fiber class, not slapping on the side?

My usecase is simple: I would like to exit main() only after all spawned fibers return. I can close channels, I can close sockets, I can kill children, but I can’t seem to find a clean way to interrupt a sleep.