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

Methods

broadcast   new   signal   wait  

Public Class methods

[Source]

     # File lib/thread.rb, line 184
184:   def initialize
185:     @waiters = []
186:   end

Public Instance methods

Wakes up all threads waiting for this lock.

[Source]

     # 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.

[Source]

     # 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

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

[Source]

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

[Validate]