Project

General

Profile

Actions

Bug #15645

closed

It is possible to escape `Mutex#synchronize` without releasing the mutex

Added by jneen (Jeanine Adkisson) about 5 years ago. Updated almost 5 years ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 2.6.1p33 (2019-01-30 revision 66950) [x86_64-linux]
[ruby-core:91705]

Description

Hello, I hope this finds you well.

I have a persistent deadlocking issue in a project that relies both on Mutex#synchronize and Thread#raise, and I believe I have reduced the problem to the following example, in which it is possible to exit a synchronize block without releasing the mutex.

mutex = Mutex.new
class E < StandardError; end

t1 = Thread.new do
  10000.times do
    begin
      mutex.synchronize do
        puts 'acquired'
        # sleep 0.01
        raise E if rand < 0.5
        puts 'releasing'
      end
    rescue E
      puts "interrupted"
    end

    puts "UNRELEASED MUTEX" if mutex.owned?
  end
end

t2 = Thread.new do
  1000.times do
    mutex.synchronize { sleep 0.01 }
    sleep 0.01
    t1.raise(E)
  end
end

t3 = Thread.new do
  1000.times do
    mutex.synchronize { sleep 0.01 }
    sleep 0.01
    t1.raise(E)
  end
end

t2.join
t3.join

I would expect mutex.owned? to always return false outside of the synchronize { ... } block, but when I run the above script, I see the following output:

; ruby tmp/testy.rb
acquired
interrupted
interrupted
UNRELEASED MUTEX
#<Thread:0x00005577aaa07860@tmp/testy.rb:4 run> terminated with exception (report_on_
exception is true):
Traceback (most recent call last):
        3: from tmp/testy.rb:5:in `block in <main>'
        2: from tmp/testy.rb:5:in `times'
        1: from tmp/testy.rb:7:in `block (2 levels) in <main>'
tmp/testy.rb:7:in `synchronize': deadlock; recursive locking (ThreadError)

I do not fully understand why this is possible, and it is possible there is a simpler example that would reproduce the issue. But it seems at least that it is necessary for two different threads to be running Thread#raise simultaneously.

Occasionally, especially if the timing of the sleep calls are tuned, the thread t1 will display an stack trace for an error E - which I believe is the expected behavior in the case that the error is raised during its rescue block.

Thank you for your time!


Related issues 1 (0 open1 closed)

Related to Ruby master - Bug #15360: "ThreadError: deadlock; recursive locking" error when recursive lock shouldn't be possibleClosedActions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0