| 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.
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
}
}
Creates a new ConditionVariable
# File lib/thread.rb, line 192
192: def initialize
193: @waiters = []
194: end
Wakes up all threads waiting for this lock.
# File lib/thread.rb, line 225
225: def broadcast
226: waiters0 = nil
227: Thread.exclusive do
228: waiters0 = @waiters.dup
229: @waiters.clear
230: end
231: for t in waiters0
232: begin
233: t.run
234: rescue ThreadError
235: end
236: end
237: end
Wakes up the first thread in line waiting for this lock.
# File lib/thread.rb, line 213
213: def signal
214: begin
215: t = @waiters.shift
216: t.run if t
217: rescue ThreadError
218: retry
219: end
220: end