Class: Ref::SafeMonitor
- Inherits:
-
Object
- Object
- Ref::SafeMonitor
- 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
-
#initialize ⇒ SafeMonitor
constructor
A new instance of SafeMonitor.
-
#lock ⇒ Object
Acquire an exclusive lock.
-
#synchronize ⇒ Object
Run a block of code with an exclusive lock.
-
#unlock ⇒ Object
Release the exclusive lock.
Constructor Details
#initialize ⇒ SafeMonitor
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
#lock ⇒ Object
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 |
#synchronize ⇒ Object
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 |
#unlock ⇒ Object
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 |