Class: TimedSemaphore

Inherits:
Object
  • Object
show all
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.

Examples:

threads = []
semaphore = TimedSemaphore.new(2, 3)

10.times do
  threads << Thread.new do
    semaphore.acquire
    puts Time.now
  end
end

threads.map(&:join)

See Also:

Author:

  • ssuljic

Instance Method Summary collapse

Constructor Details

#initialize(num_of_ops, num_of_seconds) ⇒ TimedSemaphore

Returns a new instance of TimedSemaphore.

Parameters:

  • num_of_ops (Fixnum)

    Number of operations which should be allowed in a specified time frame.

  • num_of_seconds (Fixnum)

    Period in seconds after all permits are released.



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

#acquireObject

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