From: Ken Bloom Date: 2009-03-09T12:08:19+09:00 Subject: Re: 1.9.x Thread problem On Sun, 08 Mar 2009 21:05:58 -0500, Michael Malone wrote: > Nobuyoshi Nakada wrote: >> Hi, >> >> At Mon, 9 Mar 2009 09:25:06 +0900, >> Michael Malone wrote in [ruby-talk:330697]: >> >>> If I run this using either ruby 1.9.1p0 (2009-01-30 revision 21907) >>> [i686-linux] or ruby 1.9.2dev (2009-03-05 trunk 22769) [i686-linux] I >>> get results I would not expect: >>> Joining thread , n= >>> >>> >> It hasn't been defined which thread, the created child thread or the >> creating parent thread, runs first at thread creation. In 1.8, the >> child runs first by chance. >> >> > Can you then explain why it runs consistently like this or a way in > which I can guarantee I am running in the first created child thread? I > would have expected to be inside of the child thread because the code > setting up the :index is inside the block passed to Thread.new(). And I > only put the created child Thread instances in the Queue, so I should > _only_ get child Thread instances when I call Queue#pop. I'm really not sure what you're asking. All you get from Queue#pop is child threads. The thing is that the operating system decides (and it is quite out of your control) which thread will have a chance to execute next. So apparently Ruby 1.8 always chose to let the child threads have a chance before you reached the THREADS.times loop. Ruby 1.9, on the other hand isn't giving the child threads a chance to run any code until you hit the th.join() call. Thus, when you try to access th[:index] and th [:n], the child threads haven't had a chance to update them yet. Once you run thread 0, that takes long enough that the other threads also get a chance to execute and set values for th[:index] and th[:n], and that's why those values are available. But there's no guarantees about who gets to execute when, and you shouldn't count on any. This is not a bug. Unfortunately, I don't have any ideas about a good way to ensure that the threads execute far enough to have set th[:index] and th[:n] before you print them. -- Chanoch (Ken) Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/