tagomoris / right_speed

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Methods defined in different Ractors can't be called

tagomoris opened this issue · comments

The code below causes an exception

class Yay
  def value
    "a"
  end
end

Yay.define_method(:value) { "b" }

p(yay: Yay.new.value) #=> "b"

r = Ractor.new do
  Yay.new.value
  # snippets/define_method.rb:12:in `block in <main>': defined in a different Ractor (RuntimeError)
end

p(ractor: r.take)

But Module#prepend can work as a workaround.

class Boo
  def value
    "a"
  end
end

module Wow
  def value
    "b"
  end
end

Boo.prepend(Wow)

p(boo: Boo.new.value)

Or use shareable blocks instead (from @ko1 's advice):

class Foo
  def value
    "a"
  end
end

a = "b".freeze
Foo.define_method(:value, Ractor.make_shareable(Proc.new { a }))

p(foo: Foo.new.value)

r = Ractor.new do
  Foo.new.value
end

p(ractorY: r.take)