-
-
Save yxhuvud/98ad5646eb93f2aa4533ebb7507012bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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