Class: Ref::SafeMonitor

Inherits:
Object
  • Object
show all
Defined in:
lib/ref/safe_monitor.rb

Overview

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.

Instance Method Summary collapse

Constructor Details

#initializeSafeMonitor

Returns a new instance of SafeMonitor.



11
12
13
14
15
# File 'lib/ref/safe_monitor.rb', line 11

def initialize
  @owner = nil
  @count = 0
  @mutex = defined?(Mutex) ? Mutex.new : nil
end

Instance Method Details

#lockObject

Acquire an exclusive lock.



18
19
20
21
22
23
24
25
26
27
# 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

#synchronizeObject

Run a block of code with an exclusive lock.



43
44
45
46
47
48
# File 'lib/ref/safe_monitor.rb', line 43

def synchronize
  lock
  yield
ensure
  unlock
end

#unlockObject

Release the exclusive lock.



30
31
32
33
34
35
36
37
38
39
40
# 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