Subj : Re: Challenge: Multithreading & Synchronization To : comp.programming.threads From : Giancarlo Niccolai Date : Thu May 26 2005 12:18 pm David Schwartz wrote: > >> I remember one of our Uni profs. once told us 'never ever ever read a >> shared value without some kind of memory barrier work, even if you don't >> really care about the result'. I thought I'd been shown an exception to >> his rule, but maybe his rule holds if you want your recursive mutex to be >> completely portable, and not rely on any special property of >> reading/writing an 'owner' field. > > I do know one exception. When you have a shared variable that holds an > estimate of the current time that's updated by a thread that runs every > few seconds. For a cache, if you're running a quick check to see if the > object has already been touched this second, and where there's no harm in > a false "no, it hasn't", but you want to find out if it has as quickly as > possible, a non-locked read of the time may be appropriate. There's no > harm in an incorrect read because it's just tuning the cache. > This is true for a generic "error don't care" situation; I.e. in case of a loop termination flag that is set false in another thread, and you don't care to terminate immediately, but just in a sensible time, then you may do a few extra loops after thread 1 set the stop flag to true, and before thread 2 sees it changed. But, usually the "error don't care" situation is not time sensible anyway, (i.e. macroscopic waits are involved), and so, what's the gain in not using a mutex? A few clock-cycles? So I'd stick with that uni prof saying; as I said in the other branch, when we showed the pseudo code of the for the recursive mutex, we implied that m_owner check is atomic (because we are speaking of low-level code where you must know how the machine works... we were speaking of writing a mutex). In any other situation, you should presume nothing, as DS correctly points out. Giancarlo. .