Class: ThreadLock
- Inherits:
-
Object
- Object
- ThreadLock
- Defined in:
- lib/ruby-threading-toolkit/thread_lock.rb
Instance Method Summary collapse
- #exclusive ⇒ Object
- #exclusive? ⇒ Boolean
-
#initialize ⇒ ThreadLock
constructor
A new instance of ThreadLock.
- #shared ⇒ Object
Constructor Details
#initialize ⇒ ThreadLock
Returns a new instance of ThreadLock.
20 21 22 23 24 25 26 27 28 |
# File 'lib/ruby-threading-toolkit/thread_lock.rb', line 20 def initialize @mutex = Mutex.new @exclusive_done = ConditionVariable.new @shared_done = ConditionVariable.new @exclusive = false @shared = [] end |
Instance Method Details
#exclusive ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/ruby-threading-toolkit/thread_lock.rb', line 46 def exclusive @mutex.synchronize do raise(NestingThreadLockError, "Unable to obtain exclusive lock inside another shared or exclusive lock") if @shared.include?(Thread.current) || @exclusive == Thread.current if @exclusive @exclusive_done.wait_while(@mutex) {@exclusive} end @exclusive = Thread.current unless @shared.empty? @shared_done.wait_until(@mutex) {@shared.empty?} end end yield ensure if @mutex.synchronize {@exclusive = false if @exclusive == Thread.current } == false @exclusive_done.broadcast end end |
#exclusive? ⇒ Boolean
67 68 69 |
# File 'lib/ruby-threading-toolkit/thread_lock.rb', line 67 def exclusive? @mutex.synchronize { @exclusive == Thread.current } end |
#shared ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/ruby-threading-toolkit/thread_lock.rb', line 30 def shared @mutex.synchronize do if @exclusive && @exclusive != Thread.current @exclusive_done.wait_while(@mutex) {@exclusive} end @shared << Thread.current end yield ensure @mutex.synchronize { @shared.delete_at(@shared.index(Thread.current)) if @shared.index(Thread.current)} @shared_done.signal end |