From: Scott Peacock Date: 2011-01-14T09:45:37+09:00 Subject: Re: Thread Variable race condition Hi Karan, Your problem seems to be that you are sharing state between all the threads you are creating. When you create a thread, all variables that are in scope at the point it is created are accessible to the thread. So the variable 'i' is visible to all the threads you create (which is why you can print) but it is visible to *all* the threads you create (which is why you can print duplicates). As Robert says, there's no guarantee about scheduling. So at the point you increment 'i' you could have up to 4 threads which have not yet printed. (It can't be five because you're blocking the thread that makes threads every fifth thread). In practice you're only seeing 2 at a time but it could be 3 or 4. Three or four are just really unlikely. Then when you increment 'i' they all might print but because they all access the same variable 'i' (it is in scope to them) they all print the same thing. I think you want to pass in 'i' as a variable to the thread. This will create a thread local variable that will not increment when you increment 'i' and so every thread will print the value of 'i' at the point the thread was created. i = 1 while(i < 100) t = Thread.new(i) do |i_copy| echo(i_copy) end t.join if (i % 5 == 0) i = i + 1 end Is this the problem you were looking to solve? Thanks, Scott -- Posted via http://www.ruby-forum.com/.