Class: CountingSemaphore

Inherits:
Object
  • Object
show all
Defined in:
lib/buzzcore/extra/thread_utils.rb

Overview

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



142
143
144
145
# File 'lib/buzzcore/extra/thread_utils.rb', line 142

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

Instance Method Details

#exclusiveObject Also known as: synchronize



178
179
180
181
182
183
# File 'lib/buzzcore/extra/thread_utils.rb', line 178

def exclusive
  wait
  yield
ensure
  signal
end

#signalObject Also known as: up, V



158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/buzzcore/extra/thread_utils.rb', line 158

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



147
148
149
150
151
152
153
154
155
156
# File 'lib/buzzcore/extra/thread_utils.rb', line 147

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