2009-02-11 103 views

回答

2

由於我不知道Java的警告,根據您的意見,我認爲你想要一個條件變量。谷歌的「Ruby條件變量」出現了一堆有用的頁面。 first link I get,似乎是一個很好的快速介紹條件變量特別是,而this看起來像它提供了一個更廣泛的覆蓋Ruby的線程編程。

0

我想你想要的是Thread#join

threads = [] 
10.times do 
    threads << Thread.new do 
    some_method(:foo) 
    end 
end 

threads.each { |thread| thread.join } #or threads.each(&:join) 

puts 'Done with all threads' 
+1

不是真的。連接等待,直到線程完成執行。等待暫停一個線程,直到它被通知,以便它可以恢復執行。 – Geo 2009-02-11 00:32:06

+0

啊。我的錯。我實際上並不知道Java,所以我的猜測失敗了。 – 2009-02-11 00:48:39

1

有沒有相當於notifyAll的(),但其他兩個是Thread.stop(停止當前線程)和run(呼籲停止線程,使其啓動再去)。

+2

我相信ConditionVariable#廣播相當於notifyAll() – finnw 2009-02-12 12:26:26

1

我認爲你正在尋找更像這樣的東西。它會在任何對象實例化後執行。這並不完美,特別是在Thread.stop不在互斥體中的情況下。在java中,等待一個線程,釋放一個監視器。

class Object 
    def wait 
    @waiting_threads = [] unless @waiting_threads 
    @monitor_mutex = Mutex.new unless @monitor_mutex 
    @monitor_mutex.synchronize { 
     @waiting_threads << Thread.current 
    } 
    Thread.stop 
    end 

    def notify 
    if @monitor_mutex and @waiting_threads 
     @monitor_mutex.synchronize { 
     @waiting_threads.delete_at(0).run unless @waiting_threads.empty? 
     } 
    end 
    end 

    def notify_all 
    if @monitor_mutex and @waiting_threads 
     @monitor_mutex.synchronize { 
     @waiting_threads.each {|thread| thread.run} 
     @waiting_threads = [] 
     } 
    end 
    end 
end 
7

你在找什麼是ThreadConditionVariable

require "thread" 

m = Mutex.new 
c = ConditionVariable.new 
t = [] 

t << Thread.new do 
    m.synchronize do 
    puts "A - I am in critical region" 
    c.wait(m) 
    puts "A - Back in critical region" 
    end 
end 

t << Thread.new do 
    m.synchronize do 
    puts "B - I am critical region now" 
    c.signal 
    puts "B - I am done with critical region" 
    end 
end 

t.each {|th| th.join }