| Class | ConditionVariable |
| In: |
lib/thread.rb
|
| Parent: | Object |
ConditionVariable objects augment class Mutex. Using condition variables, it is possible to suspend while in the middle of a critical section until a resource becomes available (see the discussion on page 117).
Example:
require 'thread'
mutex = Mutex.new
resource = ConditionVariable.new
a = Thread.new {
mutex.synchronize {
# Thread 'a' now needs the resource
resource.wait(mutex)
# 'a' can now have the resource
}
}
b = Thread.new {
mutex.synchronize {
# Thread 'b' has finished using the resource
resource.signal
}
}
Wakes up all threads waiting for this lock.
# File lib/thread.rb, line 217
217: def broadcast
218: waiters0 = nil
219: Thread.exclusive do
220: waiters0 = @waiters.dup
221: @waiters.clear
222: end
223: for t in waiters0
224: begin
225: t.run
226: rescue ThreadError
227: end
228: end
229: end
Wakes up the first thread in line waiting for this lock.
# File lib/thread.rb, line 205
205: def signal
206: begin
207: t = @waiters.shift
208: t.run if t
209: rescue ThreadError
210: retry
211: end
212: end