Class: Semaphore

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

Overview

Semaphore

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

Instance Method Summary collapse

Constructor Details

#initialize(initvalue = 0) ⇒ Semaphore

Returns a new instance of Semaphore.



36
37
38
39
# File 'lib/more/facets/semaphore.rb', line 36

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

Instance Method Details

#exclusiveObject Also known as: synchronize



72
73
74
75
76
77
# File 'lib/more/facets/semaphore.rb', line 72

def exclusive
  wait
  yield
ensure
  signal
end

#signalObject Also known as: up, v



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/more/facets/semaphore.rb', line 52

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



41
42
43
44
45
46
47
48
49
50
# File 'lib/more/facets/semaphore.rb', line 41

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