Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Implement ractor by Thread
using Module.new {
refine ThreadGroup do
attr_accessor :fake_ractor
end
}
class FakeRactor
def initialize(*args, name: nil, &block)
@name = name
@incoming = Thread::Queue.new
@outgoing = Thread::Queue.new
Thread.new do
ThreadGroup.new.tap do |g|
g.add Thread.current
g.fake_ractor = self
end
instance_exec(*args, &block)
end
end
attr_reader :incoming
attr_reader :outgoing
def self.current
Thread.current.group.fake_ractor
end
def self.count
raise NotImplementedError
end
def self.select(*ractors, yield_value: true, move: false)
raise NotImplementedError
end
def self.recv
current.incoming.deq
end
def send(obj, move: false)
@incoming << obj
self
end
def self.yield obj, move: false
current.outgoing << obj
end
def take
@outgoing.deq
end
alias << send
def inspect
super
end
def name
@name
end
class RemoteError
attr_reader :ractor
end
def close_incoming
@incoming.close
end
def close_outgoing
@outgoing.close
end
def close
close_incoming
close_outgoing
end
end
r = FakeRactor.new do
FakeRactor.yield FakeRactor.recv
end
r.send 42
p r.take
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment