Class: CountingSemaphore

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

Overview

Semaphore (CountingSemaphore)

Technically a semaphore is simply an integer variable which has an execution queue associated with it.

Usage

s = Semaphore.new

# to do

History

$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.



22
23
24
25
# File 'lib/carat/semaphore.rb', line 22

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

Instance Method Details

#exclusiveObject Also known as: synchronize



58
59
60
61
62
63
# File 'lib/carat/semaphore.rb', line 58

def exclusive
  wait
  yield
ensure
  signal
end

#signalObject Also known as: up, v



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/carat/semaphore.rb', line 38

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



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

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