Class: Upfluence::Utils::Semaphore
- Inherits:
-
Object
- Object
- Upfluence::Utils::Semaphore
- Defined in:
- lib/upfluence/utils/semaphore.rb
Instance Method Summary collapse
- #acquire(count = 1) ⇒ Object
-
#initialize(size) ⇒ Semaphore
constructor
A new instance of Semaphore.
- #release(count = 1) ⇒ Object
- #synchronize(count = 1, &block) ⇒ Object
Constructor Details
#initialize(size) ⇒ Semaphore
Returns a new instance of Semaphore.
4 5 6 7 8 9 |
# File 'lib/upfluence/utils/semaphore.rb', line 4 def initialize(size) @size = size @used = 0 @mutex = Mutex.new @cond = ConditionVariable.new end |
Instance Method Details
#acquire(count = 1) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/upfluence/utils/semaphore.rb', line 11 def acquire(count = 1) @mutex.synchronize do loop do break if @used + count <= @size @cond.wait(@mutex) end @used += count end end |
#release(count = 1) ⇒ Object
23 24 25 26 27 28 |
# File 'lib/upfluence/utils/semaphore.rb', line 23 def release(count = 1) @mutex.synchronize do @used -= count @cond.broadcast end end |
#synchronize(count = 1, &block) ⇒ Object
30 31 32 33 34 35 |
# File 'lib/upfluence/utils/semaphore.rb', line 30 def synchronize(count = 1, &block) acquire(count) block.call ensure release(count) end |