Skip to content

Commit

Permalink
Add spec for thread-safe autoload
Browse files Browse the repository at this point in the history
  • Loading branch information
eregon committed Jun 9, 2023
1 parent 6479623 commit b57b807
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
14 changes: 14 additions & 0 deletions spec/ruby/core/module/autoload_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -903,6 +903,20 @@ class ModuleSpecs::Autoload::Z < ModuleSpecs::Autoload::ZZ
t2_exc.should be_nil
end

it "blocks other threads until the file is done loading so no partial modules are seen" do
ModuleSpecs::Autoload.autoload :ThreadSafe, fixture(__FILE__, "autoload_thread_safe.rb")
barrier = ModuleSpecs::CyclicBarrier.new 2
ScratchPad.record(barrier)

thread = Thread.new { # starts the autoload
ModuleSpecs::Autoload::ThreadSafe.foo.should == 42
}
barrier.await
ModuleSpecs::Autoload::ThreadSafe.foo.should == 42 # ThreadSafe should only be published once the whole file is loaded

thread.join
end

# https://bugs.ruby-lang.org/issues/10892
it "blocks others threads while doing an autoload" do
file_path = fixture(__FILE__, "repeated_concurrent_autoload.rb")
Expand Down
20 changes: 20 additions & 0 deletions spec/ruby/core/module/fixtures/autoload_thread_safe.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module ModuleSpecs::Autoload
class ThreadSafe
def self.bar # to illustrate partial loading
end

barrier = ScratchPad.recorded
barrier.await

# the main thread should be waiting for this file to be fully loaded
Thread.pass until Thread.main.stop?
10.times do
Thread.pass
Thread.main.should.stop?
end

def self.foo
42
end
end
end
2 changes: 1 addition & 1 deletion spec/ruby/core/module/fixtures/classes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,7 @@ def extend_object(obj)
end

class CyclicBarrier
def initialize(count = 1)
def initialize(count)
@count = count
@state = 0
@mutex = Mutex.new
Expand Down

0 comments on commit b57b807

Please sign in to comment.