在我的主线程中,我试图从两个单独的线程中等待两个资源。我实施的方式如下:条件变量在主线程
require 'thread'
def new_thread
Thread.current[:ready_to_go] = false
puts "in thread: new thread"
sleep(5)
puts "in thread: sleep finished"
Thread.current[:ready_to_go] = true
sleep(2)
puts "in thread: back to thread again!"
end
thread1 = Thread.new do
new_thread
end
thread2 = Thread.new do
new_thread
end
# the main thread wait for ready_to_go to start
while (!(thread1[:ready_to_go] && thread2[:ready_to_go]))
sleep(0.5)
end
puts "back to main!"
sleep(8)
puts "main sleep over!"
thread1.join
thread2.join
有没有更好的方法来实现呢?我试图使用条件变量:两个线程表示条件变量,主线程等待它们。但是等待方法需要在我的主线程中有一个互斥量,我试图避免这种互斥量。
主线程不等待其他线程回来。它正在等待一些资源准备就绪(Thread.current [:ready_to_go])。主线程开始运行时,线程需要保持运行。 – ccy 2011-02-14 22:51:12