2011-02-12 48 views
0

在我的主线程中,我试图从两个单独的线程中等待两个资源。我实施的方式如下:条件变量在主线程

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 

有没有更好的方法来实现呢?我试图使用条件变量:两个线程表示条件变量,主线程等待它们。但是等待方法需要在我的主线程中有一个互斥量,我试图避免这种互斥量。

回答

0

我不熟悉的红宝石,但the first Google result for "Ruby wait for thread"说:

你可以等待特定线程通过调用线程的线程#完成连接方法。调用线程将阻塞,直到给定的线程完成。通过在每个请求程序线程上调用加入,可以确保在终止主程序之前全部三个请求都已完成。

通常最好使用同步方法来等待某件事完成,而不是循环直到达到特定状态。

+0

主线程不等待其他线程回来。它正在等待一些资源准备就绪(Thread.current [:ready_to_go])。主线程开始运行时,线程需要保持运行。 – ccy 2011-02-14 22:51:12

0

一个简单的方法是获得一个队列(我们称之为myqueue)。它的线程和位于螺纹牙模块中

而不是

Thread.current[:ready_to_go] = true 

...做

myqueue.push :ready_to_go 

然后你的主线程是:

junk = myqueue.pop # wait for thread one to push 
junk = myqueue.pop # wait for thread two to push 
# go on with your work