3

Suppose:

  • There is some object (e.g., an array a) and a condition dependent on the object (e.g., such as a.empty?).
  • Some threads other than the current thread can manipulate the object (a), so the truthness of the evaluated value of the condition changes over the time.

How can I let the current thread sleep at some point in the code and continue (wake up) by push notification when the condition is satisfied?

I do not want to do polling like this:

...
sleep 1 until a.empty?
...

Perhaps using Fiber will be a clue.

sawa
  • 165,429
  • 45
  • 277
  • 381
  • 1
    Whatever the condition is, write a hook that is invoked any time your behavior is invoked. It can hold a collection of objects, perhaps threads or fibers, that can be processed at that time. This would be similar in fashion to perhaps [this project](https://github.com/kristinalim/ruby_hooks) – vgoff Jul 14 '13 at 05:27

1 Answers1

2

Maybe I do not quite understand your question, but I guess ConditionVariable is a good approach for such problem.

So, ConditionVariable can be used to signal threads when something happens. Let's see:

require 'thread'

a = [] # array a is empty now
mutex = Mutex.new
condvar = ConditionVariable.new 

Thread.new do
  mutex.synchronize do
    sleep(5)
    a << "Hey hey!"
    # Now we have value in array; it's time to signal about it
    condvar.signal
  end
end

mutex.synchronize do
  condvar.wait(mutex)
  # This happens only after 5 seconds, when condvar recieves signal
  puts "Hey. Array a is not empty now!"
end
sawa
  • 165,429
  • 45
  • 277
  • 381
railscard
  • 1,848
  • 16
  • 12