Extended maintenance of Ruby versions 1.8.7 and 1.9.2 will end on July 31, 2014. Read more

In Files

  • thread.rb

Parent

Class/Module Index [+]

Quicksearch

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 187
def initialize
  @waiters = []
end
            

Public Instance Methods

broadcast() click to toggle source

Wakes up all threads waiting for this lock.

 
               # File thread.rb, line 220
def broadcast
  waiters0 = nil
  Thread.exclusive do
    waiters0 = @waiters.dup
    @waiters.clear
  end
  for t in waiters0
    begin
      t.run
    rescue ThreadError
    end
  end
end
            
signal() click to toggle source

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

 
               # File thread.rb, line 208
def signal
  begin
    t = @waiters.shift
    t.run if t
  rescue ThreadError
    retry
  end
end
            
wait(mutex) click to toggle source

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

 
               # File thread.rb, line 194
def wait(mutex)
  begin
    mutex.exclusive_unlock do
      @waiters.push(Thread.current)
      Thread.stop
    end
  ensure
    mutex.lock
  end
end
            

Commenting is here to help enhance the documentation. For example, code samples, or clarification of the documentation.

If you have questions about Ruby or the documentation, please post to one of the Ruby mailing lists. You will get better, faster, help that way.

If you wish to post a correction of the docs, please do so, but also file bug report so that it can be corrected for the next release. Thank you.

If you want to help improve the Ruby documentation, please visit Documenting-ruby.org.

blog comments powered by Disqus