From: Wesley J Landaker Date: 2001-08-07T07:31:21+09:00 Subject: [ruby-talk:19256] Re: Trying to get to grips with Ruby threads -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Monday 06 August 2001 3:21pm, Peter Hickman wrote: > I am trying to get to grips with threads in Ruby and I wrote (adapted > more like) the following code. What happens is each thread processes > in turn with everything pausing on the sleep in thread id 0. What I > was expecting was thread 0 would sleep and thread 1 would eat up all > the work, or at least a fair amount of it. But thread 1 does not seem > to run until thread 0 finishes and then it goes back to thread 0. > > Threads can do what I'm asking of them can't they? I need to do it in > this manner as each thread will infact also be adding work into the > work array. Thus forking would seem to be out of the question. A clue > please. > > require 'thread' > mutex = Mutex.new > > cv = ConditionVariable.new > > work = Array.new > 100.times {|i| work << "Job #{i}" } > > threads = Array.new > > 2.times {|i| > threads << Thread.new(i) {|id| > mutex.synchronize { > while 1 == 1 do > cv.wait(mutex) > if ! work.empty? then > job = work.pop > cv.signal > puts "Thread #{id} processing #{job}\n" > if id == 0 then > sleep(5) > end > else > cv.signal > break > end > end > } > } > } > > cv.signal > > threads.each {|i| i.join } 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. - -- Wesley J. Landaker - wjl@mindless.com http://www.landaker.net PGP DSS/DH Key: 0x0F338E07 PGPKey FP: 3AAA 424B B488 198E B68B C0E5 390A BACA 0F33 8E07 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6a (GNU/Linux) Comment: All your base are belong to us. iEYEARECAAYFAjtvGq8ACgkQOQq6yg8zjgcO/wCg+ojmPSAaR4W56fN3jasdD6mk EBAAoOTOk6YmoS1muFjGur8vMJdUb2F/ =qKDK -----END PGP SIGNATURE-----