a0b Subj : Re: Challenge: Multithreading & Synchronization To : comp.programming.threads From : David Schwartz Date : Mon May 23 2005 08:27 pm "doug" wrote in message news:8ptke.116937$Cq2.74293@fe2.news.blueyonder.co.uk... > > "David Schwartz" wrote in message > news:d6t6df$auh$2@nntp.webmaster.com... >> "doug" wrote in message >> news:ZyPje.1900$iq5.1180@fe1.news.blueyonder.co.uk... >>> I know where you're coming from - that's where I came from too. But >>> some folk (Peter, Giancarlo) explained that *yes*, you might read the >>> wrong value, but it doesn't matter. You're guaranteed to get the answer >>> to the question "do I own this lock" correct. >> Guaranteed by what? >> Suppose you are thread "A1". The lock is held by "A2" and transfers to >> "B1" while you are checking the owner field. What stops you from seeing >> half of each and getting "A1", and thinking you own the lock? > Ah, good point. Very good point indeed. > > I think we're assuming that reads/write of an owner field would be atomic. > But bloody good point. Yes, if you have a platform that guarantees that, then you can use that as a platform-specific optimization. But you really should implement generically first, and make platform-specific optimizations when you care about platforms where you know they are safe and when benchmarking demonstrates that the performance boost is worth the risk. > 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. And, of course, there are many platforms where 32-bit aligned reads and writes are known to be atomic. DS . 0