Skip to content

Instantly share code, notes, and snippets.

@yxhuvud
Last active August 30, 2022 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yxhuvud/98ad5646eb93f2aa4533ebb7507012bb to your computer and use it in GitHub Desktop.
Save yxhuvud/98ad5646eb93f2aa4533ebb7507012bb to your computer and use it in GitHub Desktop.
lib LibC
fun eventfd(initval : LibC::UInt, flags : LibC::Int) : LibC::Int
end
module FiberNotifier
struct Notifier
def initialize(@semaphore = false)
@eventfd = IO::FileDescriptor.new(LibC.eventfd(0, 0))
@write_buf = 1u64
@read_buf = 0u64
end
def notify
LibC.write(@eventfd.fd, pointerof(@write_buf), 8)
end
# Fetches all pending notifications, and return the count.
def listen_all
@eventfd.wait_readable { }
reset
end
def reset
LibC.read(@eventfd.fd, pointerof(@read_buf), 8)
@read_buf
end
end
struct Semaphore
def initialize
@eventfd = IO::FileDescriptor.new(LibC.eventfd(0, 1))
@write_buf = 1u64
@read_buf = 0u64
end
def notify
LibC.write(@eventfd.fd, pointerof(@write_buf), 8)
end
# Decrement value 1 step.
def listen
@eventfd.wait_readable { reset }
end
def reset
LibC.read(@eventfd.fd, pointerof(@read_buf), 8)
end
end
end
notifier = FiberNotifier::Notifier.new
semaphore = FiberNotifier::Semaphore.new
spawn do
2.times { notifier.notify }
semaphore.notify
end
spawn do
p notifier.listen_all
semaphore.notify
end
semaphore.listen
semaphore.listen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment