Parent

Files

Ref::SafeMonitor

The Monitor class in Ruby 1.8 has some bugs and also threads may not be available on all runtimes. This class provides a simple, safe re-entrant mutex as an alternative.

Public Class Methods

new() click to toggle source
# File lib/ref/safe_monitor.rb, line 11
def initialize
  @owner = nil
  @count = 0
  @mutex = defined?(Mutex) ? Mutex.new : nil
end

Public Instance Methods

lock() click to toggle source

Acquire an exclusive lock.

# File lib/ref/safe_monitor.rb, line 18
def lock
  if @mutex
    if @owner != Thread.current.object_id
      @mutex.lock
      @owner = Thread.current.object_id
    end
    @count += 1
  end
  true
end
synchronize() click to toggle source

Run a block of code with an exclusive lock.

# File lib/ref/safe_monitor.rb, line 43
def synchronize
  lock
  yield
ensure
  unlock
end
unlock() click to toggle source

Release the exclusive lock.

# File lib/ref/safe_monitor.rb, line 30
def unlock
  if @mutex
    if @owner == Thread.current.object_id
      @count -= 1
      if @count == 0
        @owner = nil
        @mutex.unlock
      end
    end
  end
end

[Validate]

Generated with the Darkfish Rdoc Generator 2.