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

Methods

broadcast   new   signal   wait  

Public Class methods

Creates a new ConditionVariable

[Source]

     # File lib/thread.rb, line 187
187:   def initialize
188:     @waiters = []
189:   end

Public Instance methods

Wakes up all threads waiting for this lock.

[Source]

     # File lib/thread.rb, line 220
220:   def broadcast
221:     waiters0 = nil
222:     Thread.exclusive do
223:       waiters0 = @waiters.dup
224:       @waiters.clear
225:     end
226:     for t in waiters0
227:       begin
228:         t.run
229:       rescue ThreadError
230:       end
231:     end
232:   end

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

[Source]

     # File lib/thread.rb, line 208
208:   def signal
209:     begin
210:       t = @waiters.shift
211:       t.run if t
212:     rescue ThreadError
213:       retry
214:     end
215:   end

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

[Source]

     # File lib/thread.rb, line 194
194:   def wait(mutex)
195:     begin
196:       mutex.exclusive_unlock do
197:         @waiters.push(Thread.current)
198:         Thread.stop
199:       end
200:     ensure
201:       mutex.lock
202:     end
203:   end

[Validate]