Class: Cute::Synchronization::Semaphore

Inherits:
Object
  • Object
show all
Defined in:
lib/cute/synchronization.rb

Instance Method Summary collapse

Constructor Details

#initialize(max) ⇒ Semaphore

Returns a new instance of Semaphore.



4
5
6
7
8
9
# File 'lib/cute/synchronization.rb', line 4

def initialize(max)
  @lock = Mutex.new
  @cond = ConditionVariable.new
  @used = 0
  @max = max
end

Instance Method Details

#acquire(n = 1) ⇒ Object



11
12
13
14
15
16
17
18
# File 'lib/cute/synchronization.rb', line 11

def acquire(n = 1)
  @lock.synchronize {
    while (n > (@max - @used)) do
      @cond.wait(@lock)
    end
    @used += n
  }
end

#relaxed_acquire(n = 1) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/cute/synchronization.rb', line 20

def relaxed_acquire(n = 1)
  taken = 0
  @lock.synchronize {
    while (@max == @used) do
      @cond.wait(@lock)
    end
    taken = (n + @used) > @max ? @max - @used : n
    @used += taken
  }
  return n - taken
end

#release(n = 1) ⇒ Object



32
33
34
35
36
37
# File 'lib/cute/synchronization.rb', line 32

def release(n = 1)
  @lock.synchronize {
    @used -= n
    @cond.broadcast
  }
end