From: "Vishnu I." Date: 2011-01-06T18:23:35+09:00 Subject: Re: Threading in ruby Hi Robert thanks for such a clear explanation. I have a couple of questions though. > In Java - which has far more sophisticated threading and memory model > than MRI - it would also be sufficient to only synchronize the index > modification. The reason is that in Java each synchronized block has > two memory barriers - one on entry and one on exit. The JVM is only > allowed to reorder execution between two memory barriers but it is > never allowed that reordering of statements moves execution of a > statement across a memory barrier. ah I see. So anything that happens before the synchronized block should have happened before whats inside the sychronized block. Is this also true in ruby? >> retrieving index too. > Yes, of course. If you want to make access to a resource thread safe > you must synchronize *all* accesses. That's the simple rule to make > code thread safe. Only the change of the Hash in the Array does not > need to be synchronized. In fact, you should strive to make > synchronized sections as short as possible to avoid unnecessary > contention. I dont follow this. If the synchrovised section has introduced a memory barrier. Then accessing the shared counter either will or will not see the updated index. But if it see's an updated index, then because of the memory barrier mentioned previously, it should see an updated item too no? > > The solution without queue would involve a ConditionVariable. This is > more appropriate than using sleep: > > https://gist.github.com/764540#file_sc2.rb thanks :) Vishnu -- Posted via http://www.ruby-forum.com/.