Last active
August 10, 2025 23:41
-
-
Save fenrir-naru/91d4224c14698df4ff527477f34ada93 to your computer and use it in GitHub Desktop.
Retrofit of Ractor in Ruby 3.5 to work like one in Ruby <= 3.4 having yield/take
This file contains hidden or 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
Ractor = Class::new(Ractor){ | |
def self.new(*args, &b) | |
out_port = Ractor::Port::new | |
res = super(out_port, *args, &(proc{|_port, *_args| | |
Ractor[:out_port] = _port | |
_args | |
} >> b)) | |
res.monitor(out_port) | |
res.define_singleton_method(:out_port){out_port} | |
res | |
end | |
def self.yield(msg, move: false) # Do not push reserved symbols(:exited and :aborted) | |
Ractor[:out_port].send(msg, move: move) # Non-blocking, which differs from the original version | |
end | |
def take | |
case res = out_port.receive | |
when :exited, :aborted; out_port.close; value | |
else; res | |
end | |
end | |
} | |
x = Ractor::new{2.times{Ractor::yield(Ractor::receive, move: true)}; 345} | |
x.send(123); x.take # => 123 | |
x.send(234); x.take # => 234 | |
x.take # => 345 | |
x.take # => Ractor::ClosedError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment