Ruby programming, ruby ​​equivalent of java wait / notify / notifyAll

I would like to know what ruby ​​alternatives to Java methods are:

  • Wait
  • will notify
  • notifyAll

Could you post a small fragment or some links?

+6
java multithreading synchronization ruby
source share
5 answers

With the caveat that I don’t know Java, based on your comments, I think you want a condition variable. Google for the "Ruby state variable" contains tons of useful pages. the first link that I get seems to be a good quick introduction to the vars state, in particular, it looks like it gives a much wider coverage of threaded programming in Ruby.

+2
source share

What you are looking for is ConditionVariable in 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 } 
+7
source share

There is no equivalent to notifyAll (), but two others: Thread.stop (stops the current thread) and run (called on the stopped thread so that it starts again).

+1
source share

I think you are looking for something similar. It will work on any instance of the object after its launch. This is not ideal, especially where Thread.stop is outside the mutex. In java, waiting on a thread, it displays a monitor.

 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 
+1
source share

I think you want 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' 
0
source share

All Articles