Class: Copland::QueryableMutex
- Inherits:
-
Mutex
- Object
- Mutex
- Copland::QueryableMutex
- Defined in:
- lib/copland/thread.rb
Overview
A subclass of Mutex that allows clients to discover which thread has the mutex locked. This is necessary for (among other things) discovering cycles in the dependency graph of services.
Instance Method Summary collapse
-
#lock ⇒ Object
Checks to see if the current thread has the mutex locked, and if it does, raises an exception.
-
#self_locked? ⇒ Boolean
Return
true
if the current thread has locked this mutex. -
#try_lock ⇒ Object
Attempts to acquire the lock.
-
#unlock ⇒ Object
Unlocks the mutex and sets the locking thread to
nil
.
Instance Method Details
#lock ⇒ Object
Checks to see if the current thread has the mutex locked, and if it does, raises an exception. Otherwise, locks the mutex and sets the locking thread to Thread.current.
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/copland/thread.rb', line 46 def lock if @locking_thread == Thread.current raise ThreadError, "an attempt was made to reacquire an existing lock " + "(this could happen if you have a circular dependency on a service)" end while (Thread.critical = true; @locked) @waiting.push Thread.current Thread.stop end @locked = true @locking_thread = Thread.current Thread.critical = false self end |
#self_locked? ⇒ Boolean
Return true
if the current thread has locked this mutex.
98 99 100 |
# File 'lib/copland/thread.rb', line 98 def self_locked? @locking_thread == Thread.current end |
#try_lock ⇒ Object
Attempts to acquire the lock. Returns true
if the lock was acquired, and false
if the mutex was already locked.
65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/copland/thread.rb', line 65 def try_lock result = false Thread.critical = true unless @locked @locked = true result = true @locking_thread = Thread.current end Thread.critical = false result end |
#unlock ⇒ Object
Unlocks the mutex and sets the locking thread to nil
.
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
# File 'lib/copland/thread.rb', line 78 def unlock return unless @locked Thread.critical = true @locked = false begin t = @waiting.shift t.wakeup if t rescue ThreadError retry end @locking_thread = nil Thread.critical = false begin t.run if t rescue ThreadError end self end |