Class: Distem::Lib::Semaphore

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

Overview

Code snippet from : gist.github.com/305986

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (Semaphore) initialize(size)

Create a new Semaphore object

Attributes

  • size The size of the semaphore



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

def initialize(size)
  raise InvalidParameterError unless size >= 0
  @size = size
  @val = @size
  @lock = Mutex.new
  @positive = ConditionVariable.new
end

Instance Attribute Details

- (Object) size (readonly)

The size of the semaphore



9
10
11
# File 'lib/distem/distemlib/semaphore.rb', line 9

def size
  @size
end

Instance Method Details

- (Object) acquire

Try to acquire a a resource



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

def acquire
  @lock.synchronize do
    if @val == 0
      @positive.wait(@lock)
    end

    @val -= 1
  end
end

- (Object) release

Leave a resource



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

def release
  @lock.synchronize do
    @val += 1
    @positive.signal
  end
end

- (Object) synchronize

Acquire then release a resource



42
43
44
45
46
47
48
49
# File 'lib/distem/distemlib/semaphore.rb', line 42

def synchronize
  acquire
  begin
    yield
  ensure
    release
  end
end