From: Robert Klemme Date: 2011-01-06T18:39:01+09:00 Subject: Re: Threading in ruby On Thu, Jan 6, 2011 at 10:23 AM, Vishnu I. wrote: >> 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? Yes. >>> 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? Yes. But there is no additional synchronization needed for access to the Array or Hash instances in the array. It is sufficient to only update the index in a synchronized block. And in fact that is the only operation that you should do there (apart from the condition variable signal). The term "memory barrier" is a concept from the JVM. AFAIK in Ruby's MRI there is no concept as thread local and global memory (which the memory barriers update). Second, a memory barrier effects *all the memory*. Whatever changes were done before it are then propagated to between memories (in JVM of course). Does that help? Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/