Class: CountingSemaphore

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

Overview

$Id: semaphore.rb,v 1.2 2003/03/15 20:10:10 fukumoto Exp $

Instance Method Summary collapse

Constructor Details

#initialize(initvalue = 0) ⇒ CountingSemaphore

Returns a new instance of CountingSemaphore.



7
8
9
10
# File 'lib/semaphore.rb', line 7

def initialize(initvalue = 0)
  @counter = initvalue
  @waiting_list = []
end

Instance Method Details

#exclusiveObject Also known as: synchronize



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

def exclusive
  wait
  yield
ensure
  signal
end

#signalObject Also known as: up, V



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/semaphore.rb', line 23

def signal
  Thread.critical = true
  begin
    if (@counter += 1) <= 0
  t = @waiting_list.shift
  t.wakeup if t
    end
  rescue ThreadError
    retry
  end
  self
ensure
  Thread.critical = false
end

#waitObject Also known as: down, P



12
13
14
15
16
17
18
19
20
21
# File 'lib/semaphore.rb', line 12

def wait
  Thread.critical = true
  if (@counter -= 1) < 0
    @waiting_list.push(Thread.current)
    Thread.stop
  end
  self
ensure
  Thread.critical = false
end