在Ruby 中,我希望同时运行两个线程,并希望后台线程定期向前台线程发送信号。在后台线程说“开始”之前,如何让前台线程阻塞?我可以想出几种方法来做到这一点,但我正在寻找最合适、最惯用的 Ruby 方法。
在代码中:
loop do # background, thread 1
sleep 3
receive_input
tell_foreground_input_is_ready # <-- how do I do this?
end
和
loop do # foreground, thread 2
wait_for_signal_from_background # <-- how do I do this?
do_something
end
(注意:后台可能会多次向前台发出信号。每次前台完成等待时,它都会重置积压。)
最佳答案
根据 this page,您需要使用条件变量和互斥体
关于Ruby 多线程 : making one thread wait for a signal from another,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2541181/