From: Justin Collins Date: 2007-11-07T03:47:24+09:00 Subject: Re: ruby thread newbie problem Bram Kuijper wrote: > Hi all, > > As a ruby newbie, I am trying to have two Threads process the > contents of one Queue. However, in my code only one Thread is processing > the contents of Queue, instead of both Threads. How can I make sure that > _both_ Threads process the Queue mentioned below? > > > This is my code: > > queue = Queue.new > queue << "$contents_of_queue" > queue << "$contents_of_queue" > queue << "$contents_of_queue" > > threads = [] > > 2.times do |thread_index| > threads[thread_index] = > Thread.new(thread_index) do | this_thread_name | > > # let each Thread work with things from the queue > while ! queue.empty? > > contents_of_queue = queue.deq > > # output Thread number > puts "executing #{contents_of_queue} " \ > + "by thread #{this_thread_name}" > > end > end > end > > This code will output: > "executing $contents_of_queue by thread 0" > "executing $contents_of_queue by thread 0" > "executing $contents_of_queue by thread 0" > > my question is: why will thread 1 never show up? > > thanks, > Bram Thread 1 isn't showing up because Thread 0 empties the queue before Thread 1 even gets to run. Before while ! queue.empty? add puts "This is thread #{this_thread_name}" and you'll see that they do both run, it's just the second thread doesn't need to do anything. -Justin