Class: Concurrent::Selectable::Semaphore
- Defined in:
- lib/concurrent/selectable/semaphore.rb
Overview
A Semaphore is a counter which can be atomically incremented and decremented; attempts to decrement the counter below zero will block.
Instance Method Summary collapse
- #exclusive ⇒ Object (also: #synchronize)
-
#initialize(count = 0) ⇒ Semaphore
constructor
Creates a semaphore with the given initial
count. -
#nonzero? ⇒ Boolean
Returns true if the count is currently nonzero (additional external synchronization is usually required if other threads can modify the semaphore).
-
#signal ⇒ Object
(also: #put, #up, #v)
Increments the semaphore.
-
#wait(blocking = true) ⇒ Object
(also: #get, #down, #p)
Decrements the semaphore, blocking if its count is already zero and
blockingis true. -
#zero? ⇒ Boolean
Returns true if the count is currently zero (additional external synchronization is usually required if other threads can modify the semaphore).
Methods inherited from Base
Constructor Details
#initialize(count = 0) ⇒ Semaphore
Creates a semaphore with the given initial count
45 46 47 48 49 |
# File 'lib/concurrent/selectable/semaphore.rb', line 45 def initialize(count=0) super() @lock = ::Mutex.new @count = count end |
Instance Method Details
#exclusive ⇒ Object Also known as: synchronize
82 83 84 85 86 87 88 89 |
# File 'lib/concurrent/selectable/semaphore.rb', line 82 def exclusive wait begin yield ensure signal end end |
#nonzero? ⇒ Boolean
Returns true if the count is currently nonzero (additional external synchronization is usually required if other threads can modify the semaphore)
102 103 104 |
# File 'lib/concurrent/selectable/semaphore.rb', line 102 def nonzero? @lock.synchronize { @count.nonzero? } end |
#signal ⇒ Object Also known as: put, up, v
Increments the semaphore
52 53 54 55 56 57 58 |
# File 'lib/concurrent/selectable/semaphore.rb', line 52 def signal @lock.synchronize do internal_set if @count.zero? @count += 1 end self end |
#wait(blocking = true) ⇒ Object Also known as: get, down, p
Decrements the semaphore, blocking if its count is already zero and blocking is true.
65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/concurrent/selectable/semaphore.rb', line 65 def wait(blocking=true) loop do @lock.synchronize do if @count.nonzero? @count -= 1 internal_reset if @count.zero? return self end end return nil unless blocking super() end end |
#zero? ⇒ Boolean
Returns true if the count is currently zero (additional external synchronization is usually required if other threads can modify the semaphore)
95 96 97 |
# File 'lib/concurrent/selectable/semaphore.rb', line 95 def zero? @lock.synchronize { @count.zero? } end |