Extended maintenance of Ruby 1.9.3 ended on February 23, 2015. Read more

In Files

  • thread.rb

Parent

Object

Class/Module Index [+]

Quicksearch
No matching classes.

ConditionVariable

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
 }
}

Public Class Methods

new() click to toggle source

Creates a new ConditionVariable

 
 # File thread.rb, line 54
def initialize
 @waiters = []
 @waiters_mutex = Mutex.new
end
 

Public Instance Methods

broadcast() click to toggle source

Wakes up all threads waiting for this lock.

 
 # File thread.rb, line 96
def broadcast
 # TODO: incomplete
 waiters0 = nil
 @waiters_mutex.synchronize do
 waiters0 = @waiters.dup
 @waiters.clear
 end
 for t in waiters0
 begin
 t.run
 rescue ThreadError
 end
 end
 self
end
 
signal() click to toggle source

Wakes up the first thread in line waiting for this lock.

 
 # File thread.rb, line 83
def signal
 begin
 t = @waiters_mutex.synchronize { @waiters.shift }
 t.run if t
 rescue ThreadError
 retry
 end
 self
end
 
wait(mutex, timeout=nil) click to toggle source

Releases the lock held in mutex and waits; reacquires the lock on wakeup.

If timeout is given, this method returns after timeout seconds passed, even if no other thread doesn't signal.

 
 # File thread.rb, line 65
def wait(mutex, timeout=nil)
 begin
 # TODO: mutex should not be used
 @waiters_mutex.synchronize do
 @waiters.push(Thread.current)
 end
 mutex.sleep timeout
 ensure
 @waiters_mutex.synchronize do
 @waiters.delete(Thread.current)
 end
 end
 self
end
 

AltStyle によって変換されたページ (->オリジナル) /