Class: Synapse::PublicLock
- Inherits:
-
Object
- Object
- Synapse::PublicLock
- Defined in:
- lib/synapse/common/concurrency/public_lock.rb
Overview
Lock that tracks the thread owning the lock and any waiting threads
Instance Attribute Summary collapse
-
#owner ⇒ Thread
readonly
The current owner of the thread, if any.
-
#waiting ⇒ Array
readonly
The list of threads waiting for this lock.
Instance Method Summary collapse
- #initialize ⇒ undefined constructor
- #lock ⇒ undefined
-
#owned? ⇒ Boolean
Returns true if the calling thread owns this lock.
-
#owned_by?(thread) ⇒ Boolean
Returns true if the given thread owns this lock.
- #synchronize ⇒ undefined
-
#try_lock ⇒ Boolean
].
- #unlock ⇒ undefined
Constructor Details
#initialize ⇒ undefined
11 12 13 14 |
# File 'lib/synapse/common/concurrency/public_lock.rb', line 11 def initialize @mutex = Mutex.new @waiting = Array.new end |
Instance Attribute Details
#owner ⇒ Thread (readonly)
Returns The current owner of the thread, if any.
5 6 7 |
# File 'lib/synapse/common/concurrency/public_lock.rb', line 5 def owner @owner end |
#waiting ⇒ Array (readonly)
Returns The list of threads waiting for this lock.
8 9 10 |
# File 'lib/synapse/common/concurrency/public_lock.rb', line 8 def waiting @waiting end |
Instance Method Details
#lock ⇒ undefined
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/synapse/common/concurrency/public_lock.rb', line 44 def lock @mutex.synchronize do if @owner == Thread.current raise ThreadError, 'Lock is already owned by the current thread' end while @owner @waiting.push Thread.current begin @mutex.sleep ensure @waiting.delete Thread.current end end @owner = Thread.current end end |
#owned? ⇒ Boolean
Returns true if the calling thread owns this lock
20 21 22 |
# File 'lib/synapse/common/concurrency/public_lock.rb', line 20 def owned? @owner == Thread.current end |
#owned_by?(thread) ⇒ Boolean
Returns true if the given thread owns this lock
26 27 28 |
# File 'lib/synapse/common/concurrency/public_lock.rb', line 26 def owned_by?(thread) @owner == thread end |
#synchronize ⇒ undefined
32 33 34 35 36 37 38 39 40 |
# File 'lib/synapse/common/concurrency/public_lock.rb', line 32 def synchronize lock begin yield ensure unlock rescue nil end end |
#try_lock ⇒ Boolean
Returns ].
81 82 83 84 85 86 87 88 89 90 91 92 93 |
# File 'lib/synapse/common/concurrency/public_lock.rb', line 81 def try_lock @mutex.synchronize do if @owner == Thread.current raise ThreadError, 'Lock is already owned by the current thread' end return false if @owner @owner = Thread.current end true end |
#unlock ⇒ undefined
66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/synapse/common/concurrency/public_lock.rb', line 66 def unlock @mutex.synchronize do if @owner == Thread.current @owner = nil first_waiter = @waiting.first first_waiter.wakeup if first_waiter else raise ThreadError, 'Lock is not owned by the current thread' end end end |