ruby线程编程,ruby相当于java wait / notify / notifyAll

时间:2009-02-11 00:22:22

标签: java ruby multithreading synchronization

我想知道ruby的Java方法的替代品是什么:

  • 等待
  • 通知
  • notifyAll的

你能发一个小片段或一些链接吗?

5 个答案:

答案 0 :(得分:7)

您要找的是ConditionVariable中的Thread

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 }

答案 1 :(得分:2)

根据您的评论,我不知道Java的警告,我认为您需要一个条件变量。谷歌的“Ruby条件变量”提出了一堆有用的页面。 first link I get似乎是对条件变量的一个很好的快速介绍,而this看起来它更广泛地涵盖了Ruby中的线程编程。

答案 2 :(得分:1)

没有与notifyAll()相同的,但是其他两个是Thread.stop(停止当前线程)和run(在停止的线程上调用以使其再次开始)。

答案 3 :(得分: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

答案 4 :(得分: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'