Reputation: 132187
In Ruby, I want to have two threads running at the same time, and want the background thread to periodically signal the foreground thread. How do I get the foreground thread to block until the background thread says 'go'? I can think of a few ways to do it, but am after the most appropriate, idiomatic Ruby method.
In code:
loop do # background, thread 1
sleep 3
receive_input
tell_foreground_input_is_ready # <-- how do I do this?
end
and
loop do # foreground, thread 2
wait_for_signal_from_background # <-- how do I do this?
do_something
end
(note: background may signal multiple times to the foreground. each time foreground finishes waiting, it resets backlog.)
Upvotes: 2
Views: 4792
Reputation: 968
Here's an clean and brief implementation: http://emptysqua.re/blog/an-event-synchronization-primitive-for-ruby/
Upvotes: 0
Reputation: 132187
Turns out this works quite nicely:
require 'thread'
queue = Queue.new
Thread.new do
100.times do |i|
sleep 1
queue.enq i
end
end
loop do
print "waiting... "
puts queue.deq # this function blocks.
end
Upvotes: 1