Class: Distem::Lib::Synchronization::Semaphore

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

Instance Method Summary (collapse)

Constructor Details

- (Semaphore) initialize(max)

Returns a new instance of Semaphore



7
8
9
10
11
12
# File 'lib/distem/distemlib/synchronization.rb', line 7

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

Instance Method Details

- (Object) acquire(n = 1)



14
15
16
17
18
19
20
21
# File 'lib/distem/distemlib/synchronization.rb', line 14

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

- (Object) relaxed_acquire(n = 1)



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

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

- (Object) release(n = 1)



35
36
37
38
39
40
# File 'lib/distem/distemlib/synchronization.rb', line 35

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