Skip to content

Commit

Permalink
Add specs for ractors access to module instance variables
Browse files Browse the repository at this point in the history
  • Loading branch information
dushyantss committed May 31, 2023
1 parent 109d976 commit f0bc41c
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
34 changes: 34 additions & 0 deletions language/fixtures/variables.rb
Original file line number Diff line number Diff line change
Expand Up @@ -154,4 +154,38 @@ class Node
attr_accessor :left, :right
end
end

module RactorAccess
singleton_class.attr_accessor :ivar

SHAREABLE_VALUE = 3
UNSHAREABLE_VALUE = "3"
WRITE_VALUE = 4

class << self
def read_in_ractor(shareable = true)
run_in_ractor(shareable, :read)
end

def write_in_ractor(shareable = true)
run_in_ractor(shareable, :write)
end

def run_in_ractor(shareable, type)
@ivar = shareable ? SHAREABLE_VALUE : UNSHAREABLE_VALUE

r = Ractor.new(type) do |type|
if type == :read
RactorAccess.ivar
else
RactorAccess.ivar = WRITE_VALUE
end
rescue => e
e
end

r.take
end
end
end
end
45 changes: 45 additions & 0 deletions language/variables_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -937,3 +937,48 @@ def obj.foobar; $specs_uninitialized_global_variable_lazy ||= 42; end
end
end
end

describe "Module instance variables within Ractors" do
context "when the instance variable is shareable" do
ruby_version_is ""..."3.1" do
it "raises Isolation error if read from a non-main Ractor" do
result = VariablesSpecs::RactorAccess.read_in_ractor
result.should be_an_instance_of(Ractor::IsolationError)
end
end

ruby_version_is "3.1" do
it "can be read from a non-main Ractor" do
result = VariablesSpecs::RactorAccess.read_in_ractor
result.should == 3
end
end

it "raises Isolation error if written to in a non-main Ractor" do
result = VariablesSpecs::RactorAccess.write_in_ractor
result.should be_an_instance_of(Ractor::IsolationError)
end

it "raises no error if read/written in the main Ractor" do
VariablesSpecs::RactorAccess.ivar = 5
VariablesSpecs::RactorAccess.ivar.should == 5
end
end

context "when the instance variable is not shareable" do
it "raises Isolation error if read from a non-main Ractor" do
result = VariablesSpecs::RactorAccess.read_in_ractor(false)
result.should be_an_instance_of(Ractor::IsolationError)
end

it "raises Isolation error if written to in a non-main Ractor" do
result = VariablesSpecs::RactorAccess.write_in_ractor(false)
result.should be_an_instance_of(Ractor::IsolationError)
end

it "raises no error if read/written in the main Ractor" do
VariablesSpecs::RactorAccess.ivar = "totally different"
VariablesSpecs::RactorAccess.ivar.should == "totally different"
end
end
end

0 comments on commit f0bc41c

Please sign in to comment.