From: Robert Klemme Date: 2011-01-06T20:19:57+09:00 Subject: Re: Threading in ruby On Thu, Jan 6, 2011 at 11:49 AM, Vishnu I. wrote: >> 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? > > oops Im sorry I wasnt clear. My question was why would I need to > synchronize on the read of the index variable if the synchronized write > has created a memory barrier between the updation of the list item and > the index update? Thats the only piece i couldnt follow Ah, I see. The reason is simple: if the thread reading the resource does not synchronize there is no memory barrier and hence no guarantee that it will read a current value. The writing thread may have published the current state to global memory but your reading thread does not necessarily have imported that change. If you want to read more I suggest you google for "double checked locking broken". You'll find some articles which dissect this seemingly good idea. From your other mail: > hmm ok Im confused now. Say the main thread completes really quickly and > fires available.signal 10 times in 2 minutes. Meanwhile say the updater > has only updated twice. Wont the third update wait forever since there > is no one left to signal? No, because the updater won't block if it sees that there is still work to do (i <= index). It will simply continue. You can easily test this out by inserting a sleep in the updater. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/