File: reentrant_mutex_spec.rb

package info (click to toggle)
ruby-rspec 3.13.0c0e0m0s1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,856 kB
  • sloc: ruby: 70,868; sh: 1,423; makefile: 99
file content (60 lines) | stat: -rw-r--r-- 2,082 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
require 'rspec/support/reentrant_mutex'
require 'thread_order'

# There are no assertions specifically
# They are pass if they don't deadlock
RSpec.describe RSpec::Support::ReentrantMutex do
  let!(:mutex) { described_class.new }
  let!(:order) { ThreadOrder.new }
  after { order.apocalypse! }

  it 'can repeatedly synchronize within the same thread' do
    mutex.synchronize { mutex.synchronize { } }
  end

  it 'locks other threads out while in the synchronize block' do
    order.declare(:before) { mutex.synchronize { } }
    order.declare(:within) { mutex.synchronize { } }
    order.declare(:after)  { mutex.synchronize { } }

    order.pass_to :before, :resume_on => :exit
    mutex.synchronize { order.pass_to :within, :resume_on => :sleep }
    order.pass_to :after, :resume_on => :exit
  end

  it 'resumes the next thread once all its synchronize blocks have completed' do
    order.declare(:thread) { mutex.synchronize { } }
    mutex.synchronize { order.pass_to :thread, :resume_on => :sleep }
    order.join_all
  end

  # On Ruby 3.1.3+, 3.2.0 and RUBY_HEAD the raise in this spec can
  # bypass the `raise_error` capture and break this spec but
  # it is not sufficient to pend it as the raise can escape to the other
  # threads somehow therefore poisoning them so its skipped entirely.
  # This is a temporary work around to allow green cross project builds but
  # needs a fix.
  if RUBY_VERSION >= '3.0' && RUBY_VERSION < '3.1.3' && !ENV['RUBY_HEAD']
    it 'waits when trying to lock from another Fiber' do
      mutex.synchronize do
        ready = false
        f = Fiber.new do
          expect {
            ready = true
            mutex.send(:enter)
            raise 'should reach here: mutex is already locked on different Fiber'
          }.to raise_error(Exception, 'waited correctly')
        end

        main_thread = Thread.current

        t = Thread.new do
          Thread.pass until ready && main_thread.stop?
          main_thread.raise Exception, 'waited correctly'
        end
        f.resume
        t.join
      end
    end
  end
end