Class: SharedBroker::Concurrency::Semaphore

Inherits:
Object
  • Object
show all
Defined in:
lib/shared_broker/concurrency/semaphore.rb

Instance Method Summary collapse

Constructor Details

#initialize(limit) ⇒ Semaphore

Returns a new instance of Semaphore.



8
9
10
11
12
13
14
15
16
17
# File 'lib/shared_broker/concurrency/semaphore.rb', line 8

def initialize(limit)
  unless limit.is_a?(Integer) && limit > 0
    raise ArgumentError, "Expected limit to be a positive Integer, got: #{limit.inspect} (class: #{limit.class})"
  end

  @limit = limit
  @count = 0
  @mutex = Mutex.new
  @cond = ConditionVariable.new
end

Instance Method Details

#acquireObject



19
20
21
22
23
24
25
26
# File 'lib/shared_broker/concurrency/semaphore.rb', line 19

def acquire
  @mutex.synchronize do
    while @count >= @limit
      @cond.wait(@mutex)
    end
    @count += 1
  end
end

#releaseObject



28
29
30
31
32
33
# File 'lib/shared_broker/concurrency/semaphore.rb', line 28

def release
  @mutex.synchronize do
    @count -= 1
    @cond.signal
  end
end

#synchronizeObject



35
36
37
38
39
40
41
42
# File 'lib/shared_broker/concurrency/semaphore.rb', line 35

def synchronize
  acquire
  begin
    yield
  ensure
    release
  end
end