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.



6
7
8
9
10
11
# File 'lib/cute/synchronization.rb', line 6

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

Instance Method Details

#acquire(n = 1) ⇒ Object



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

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

#relaxed_acquire(n = 1) ⇒ Object



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

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



34
35
36
37
38
39
# File 'lib/cute/synchronization.rb', line 34

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