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.
6 7 8 9 10 11 |
# File 'lib/libosctl/mutex.rb', line 6 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
16 17 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 |
# File 'lib/libosctl/mutex.rb', line 16 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 raise Timeout if @thread && is_timeout end @thread = Thread.current end nil end |
#locked? ⇒ Boolean
Returns true if this lock is currently held by some thread
88 89 90 |
# File 'lib/libosctl/mutex.rb', line 88 def locked? sync { !@thread.nil? } end |
#owned? ⇒ Boolean
Returns true if this lock is currently held by current thread
93 94 95 |
# File 'lib/libosctl/mutex.rb', line 93 def owned? sync { @thread == Thread.current } end |
#sleep(timeout = nil, lock_timeout = nil) ⇒ Object
Release the lock and sleep, then reaquire it
81 82 83 84 85 |
# File 'lib/libosctl/mutex.rb', line 81 def sleep(timeout = nil, lock_timeout = nil) unlock Kernel.sleep(*(timeout ? [timeout] : [])) lock(lock_timeout) end |
#sync ⇒ Object (protected)
99 100 101 |
# File 'lib/libosctl/mutex.rb', line 99 def sync(&) @mutex.synchronize(&) end |
#synchronize(timeout = nil) ⇒ Object
Execute a block with the lock
65 66 67 68 69 70 71 72 73 |
# File 'lib/libosctl/mutex.rb', line 65 def synchronize(timeout = nil) lock(timeout) begin yield ensure unlock end end |
#unlock ⇒ Object
Release the lock
51 52 53 54 55 56 57 58 59 60 |
# File 'lib/libosctl/mutex.rb', line 51 def unlock sync do raise ThreadError, 'attempted to unlock mutex owned by another thread' unless @thread == Thread.current @thread = nil @cond.signal if @queue > 0 end nil end |