From: Robert Klemme Date: 2009-10-10T00:04:53+09:00 Subject: Re: Green Threads - I want them to thrash... 2009/10/9 Matt Brooks : > All Day I have tried to accomplish the following using threads, and just > could not get it to work.  I want them to thrash back and forth having > the power to do stuff.... > > I want two threads to execute and fight each other to send commands to a > unit.  With each thread they just call methods with certain arguments. > I want them to send the commands at the same time. > > I guess I am realizing that isn't possible, only one will have control > at a time, thats fine, I want them to pass control to each other > continously, seemingly randomly to me from the outside. > > Also in both threads i have a forever loop. > > so for example > > a = Thread.new do > loop do > method that sends commands, about 60 of them > end > end > > > b = Thread.new do > loop do > method that sends different commands, about 20 of them > end > end > > > > no matter what, thread a only runs a few commands before thead b takes > over forever, and thread a never executes again. > > To combat the problem I tried doing this after the creation of the > threads, in main I guess you call it... > >  loop do >  a.priority = -1 >  b.priority = -2 >  sleep(50) >  b.priority = -1 >  a.priority = -2 >  end > > > I also tried positioning Thread.pass randomly throughout the two > threads, hoping that would tell the thread, hey let the other guy have a > chance, then that thread would get to his Thread.pass meaning let the > first guy have a chance to send some stuff!! > > All these ways have some outcome, just the second thread executes > forever.... > > Any ideas, thank you very much for the help!! You did not mention the version you are using, so I assume it was 1.8ish. It does work on 1.9, but it takes some time: 17:00:10 desktop$ cat th.rb require 'thread' m = Mutex.new (1..2).map do |i| Thread.new i do |ii| 20000.times do m.synchronize do puts ii end end end end.each {|th| th.join} 17:00:16 desktop$ allruby th.rb | uniq CYGWIN_NT-5.1 padrklemme1 1.5.25(0.156/4/2) 2008-06-12 19:34 i686 Cygwin ======================================== ruby 1.8.7 (2008-08-11 patchlevel 72) [i386-cygwin] 1 2 ======================================== ruby 1.9.1p129 (2009-05-12 revision 23412) [i386-cygwin] 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 17:00:20 desktop$ Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/