Class: OsCtl::Lib::Mutex
- Inherits:
-
Object
- Object
- OsCtl::Lib::Mutex
- Defined in:
- lib/libosctl/mutex.rb
Overview
Extended mutex with an optional timeout on lock
Defined Under Namespace
Classes: Timeout
Instance Method Summary collapse
-
#initialize ⇒ Mutex
constructor
A new instance of Mutex.
-
#lock(timeout = nil) ⇒ Object
Attempts to grab the lock and waits if it isn't available.
-
#locked? ⇒ Boolean
Returns true if this lock is currently held by some thread.
-
#owned? ⇒ Boolean
Returns true if this lock is currently held by current thread.
-
#sleep(timeout = nil, lock_timeout = nil) ⇒ Object
Release the lock and sleep, then reaquire it.
- #sync ⇒ Object protected
-
#synchronize(timeout = nil) ⇒ Object
Execute a block with the lock.
-
#unlock ⇒ Object
Release the lock.
Constructor Details
#initialize ⇒ Mutex
Returns a new instance of Mutex.
8 9 10 11 12 13 |
# File 'lib/libosctl/mutex.rb', line 8 def initialize @mutex = ::Mutex.new @cond = ConditionVariable.new @thread = nil @queue = 0 end |
Instance Method Details
#lock(timeout = nil) ⇒ Object
Attempts to grab the lock and waits if it isn't available
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/libosctl/mutex.rb', line 18 def lock(timeout = nil) t = Time.now is_timeout = false sync do if @thread @queue += 1 loop do now = Time.now if @thread.nil? break elsif timeout && (now - t) >= timeout is_timeout = true break end @cond.wait(@mutex, timeout && (timeout - (now - t))) end @queue -= 1 if @thread && is_timeout raise Timeout else @thread = Thread.current end else @thread = Thread.current end end nil end |
#locked? ⇒ Boolean
Returns true if this lock is currently held by some thread
98 99 100 |
# File 'lib/libosctl/mutex.rb', line 98 def locked? sync { !@thread.nil? } end |
#owned? ⇒ Boolean
Returns true if this lock is currently held by current thread
103 104 105 |
# File 'lib/libosctl/mutex.rb', line 103 def owned? sync { @thread == Thread.current } end |
#sleep(timeout = nil, lock_timeout = nil) ⇒ Object
Release the lock and sleep, then reaquire it
91 92 93 94 95 |
# File 'lib/libosctl/mutex.rb', line 91 def sleep(timeout = nil, lock_timeout = nil) unlock Kernel.sleep(*(timeout ? [timeout] : [])) lock(lock_timeout) end |
#sync ⇒ Object (protected)
108 109 110 |
# File 'lib/libosctl/mutex.rb', line 108 def sync @mutex.synchronize { yield } end |
#synchronize(timeout = nil) ⇒ Object
Execute a block with the lock
75 76 77 78 79 80 81 82 83 |
# File 'lib/libosctl/mutex.rb', line 75 def synchronize(timeout = nil) lock(timeout) begin yield ensure unlock end end |
#unlock ⇒ Object
Release the lock
58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/libosctl/mutex.rb', line 58 def unlock sync do if @thread == Thread.current @thread = nil @cond.signal if @queue > 0 else raise ThreadError, 'attempted to unlock mutex owned by another thread' end end nil end |