Class: Async::Background::Runtime::Semaphore

Inherits:
Object
  • Object
show all
Defined in:
lib/async/background/runtime/semaphore.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(limit) ⇒ Semaphore

Returns a new instance of Semaphore.

Raises:

  • (ArgumentError)


9
10
11
12
13
14
15
# File 'lib/async/background/runtime/semaphore.rb', line 9

def initialize(limit)
  @limit = Integer(limit)
  raise ArgumentError, 'limit must be >= 1' unless @limit.positive?

  @available = @limit
  @waiting = WaitList.new
end

Instance Attribute Details

#limitObject (readonly)

Returns the value of attribute limit.



7
8
9
# File 'lib/async/background/runtime/semaphore.rb', line 7

def limit
  @limit
end

Instance Method Details

#acquireObject



20
21
22
23
24
25
26
27
28
29
# File 'lib/async/background/runtime/semaphore.rb', line 20

def acquire
  wait
  return @available unless block_given?

  begin
    yield
  ensure
    release
  end
end

#availableObject



17
# File 'lib/async/background/runtime/semaphore.rb', line 17

def available = @available

#releaseObject



31
32
33
34
35
36
37
38
39
# File 'lib/async/background/runtime/semaphore.rb', line 31

def release
  while (node = @waiting.shift)
    node.grant!
    return @available if node.resume
  end

  @available += 1
  @available
end

#waitingObject



18
# File 'lib/async/background/runtime/semaphore.rb', line 18

def waiting = @waiting.size