From: kjana@... (YANAGAWA Kazuhisa) Date: 2001-08-08T19:54:17+09:00 Subject: [ruby-talk:19370] Re: Trying to get to grips with Ruby threads 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.