Class: TimedSemaphore
- Inherits:
-
Object
- Object
- TimedSemaphore
- Defined in:
- lib/timed_semaphore.rb
Overview
TimedSemaphore is a specialized implementation of a Semaphore that gives a number of permits in a given time frame. A use case for it is to limit the load on a resource. The idea is taken from the Apache Commons Lang package.
Instance Method Summary collapse
-
#acquire ⇒ Object
Tries to acquire a permit from the semaphore.
-
#initialize(num_of_ops, num_of_seconds) ⇒ TimedSemaphore
constructor
A new instance of TimedSemaphore.
Constructor Details
#initialize(num_of_ops, num_of_seconds) ⇒ TimedSemaphore
Returns a new instance of TimedSemaphore.
28 29 30 31 32 33 34 35 |
# File 'lib/timed_semaphore.rb', line 28 def initialize(num_of_ops, num_of_seconds) @count = 0 @limit = num_of_ops @period = num_of_seconds @lock = Monitor.new @condition = @lock.new_cond @timer = nil end |
Instance Method Details
#acquire ⇒ Object
Tries to acquire a permit from the semaphore. This method will block if the limit for the current period has already been reached. The first call starts a timer thread for releasing all permits, which makes the semaphore active
41 42 43 44 45 46 47 |
# File 'lib/timed_semaphore.rb', line 41 def acquire synchronize do @condition.wait while @limit > 0 && @count == @limit @count += 1 start_timer if @timer.nil? end end |