From: Peter Hickman Date: 2001-08-09T05:58:07+09:00 Subject: [ruby-talk:19393] Re: Trying to get to grips with Ruby threads Thank you very much. Your code example does just what I was expecting mine to do. Thank you again for taking the time to craft such a useful code. Now I will get on with the rest of the nightmare that I have in mind. Thanks. "YANAGAWA Kazuhisa" wrote in message news:AT8c7.5520$qm1.48139@e420r-atl3.usenetserver.com... > In message <997216964.15259.0.nnrp-10.9e980a61@news.demon.co.uk> > peterhi@shake.demon.co.uk writes: > > > > Sleeping does not release the mutex... so thread #1 is always going to > > > be waiting for thread #0 to stop sleeping, as thread #0 owns the mutex. > > > > I thought that as well. However the cv.signal is before the sleep and so the > > mutex should be available. Or so I think. > > ConditionVariable#signal only signals some condition is met --- Mutex > is not released. > > On ConditionVariable#wait, the caller thread releases Mutex and passes > execution to another thread which may awake the waiting thread by > calling ConditionVariable#signal. > > > Indeed, truely critical region in your code is only getting an > existent job from the bag of jobs. In this case you don't have to use > ConditionVariables, like following: > > > require "thread" > > mutex = Mutex.new > work = (1..100).collect { |i| "job #{i}" } > > threads = [] > 2.times do > |i| > threads << Thread.new(i) do > |id| > job = nil > while true > mutex.synchronize do > if not work.empty? > job = work.pop > else > job = :nojobs > end > end > break if job == :nojobs > > puts "Thread #{id} gets #{job}" > if id == 0 > sleep(5) > end > end > end > end > > threads.each { |t| t.join } > > > But more likely to use Queue which implements a synchronized queue. > > > -- > kjana@os.xaxon.ne.jp August 8, 2001 > Haste makes waste. > >