简体   繁体   English

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

[英]ruby thread programming , ruby equivalent of java wait/notify/notifyAll

I would like to know what are ruby's alternatives to the Java methods : 我想知道ruby是Java方法的替代品:

  • wait 等待
  • notify 通知
  • notifyAll notifyAll的

Could you please post a small snippet or some links ? 你能发一个小片段或一些链接吗?

What you are looking for is ConditionVariable in Thread : 您正在寻找的是Thread ConditionVariable

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 }

With the caveat that I don't know Java, based on your comments, I think that you want a condition variable. 根据你的评论,我不知道Java的警告,我认为你想要一个条件变量。 Google for "Ruby condition variable" comes up with a bunch of useful pages. 谷歌的“Ruby条件变量”提出了一堆有用的页面。 The first link I get , seems to be a nice quick introduction to condition vars in particular, while this looks like it gives a much broader coverage of threaded programming in Ruby. 我得到第一个链接似乎是对条件变量的一个很好的快速介绍,而看起来它提供了更广泛的Ruby中的线程编程的覆盖范围。

I think you're looking for something more like this. 我想你正在寻找更像这样的东西。 It'll work on any object instantiated after this gets executed. 它将适用于执行此操作后实例化的任何对象。 It's not perfect, particularly where Thread.stop is outside the mutex. 它并不完美,特别是在Thread.stop位于互斥锁之外的情况下。 In java, waiting on a thread, releases a monitor. 在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

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

I think what you want is Thread#join 我想你想要的是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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM