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 192
192:   def initialize
193:     @waiters = []
194:   end

Public Instance methods

Wakes up all threads waiting for this lock.

[Source]

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

[Source]

     # 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

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

[Source]

     # File lib/thread.rb, line 199
199:   def wait(mutex)
200:     begin
201:       mutex.exclusive_unlock do
202:         @waiters.push(Thread.current)
203:         Thread.stop
204:       end
205:     ensure
206:       mutex.lock
207:     end
208:   end

[Validate]