aaa90210
aaa90210

Reputation: 12093

Ruby Mutex Synchronize without wait

http://ruby-doc.org/core-1.9.3/Mutex.html

Is there a way for Mutex.Synchronize to return immediately rather than waiting to obtain the lock, if it is being held by another thread at the time?

In other words, the same behavior as try_lock.

Upvotes: 0

Views: 799

Answers (1)

Stefan
Stefan

Reputation: 114178

synchronize merely

Obtains a lock, runs the block, and releases the lock when the block completes.

Here's Rubinius' implementation

class Mutex
  def synchronize
    lock
    begin
      yield
    ensure
      unlock
    end
  end
end

You can easily adopt this to write your own try_synchronize:

class Mutex
  def try_synchronize
    return unless try_lock
    begin
      yield
    ensure
      unlock
    end
  end
end

MRI throws an exception if no block is given, so you might want to add a:

raise ThreadError, 'must be called with a block' unless block_given?

Upvotes: 4

Related Questions