Hi Ulrich, Ulrich Hertlein wrote: > On 16/10/09 6:37 PM, Cory Riddell wrote: >> Ulrich Hertlein wrote: >>> ... >>> >>> Yes, CPUs usually have their own caches and data can be different in >>> the different caches. However, this isn't what synchronization is >>> solving. This problem (cache coherency) is handled by the hardware. >>> >>> The reason you need to do locking is because two threads (which may or >>> may not run on separate cores) might alter the same data in ways so >>> that the result is no longer sane. >>> >> ... >> I thought cache coherency depended on cues from the software. For >> example, acquiring or releasing a mutex forces any pending writes to >> complete then flushed the caches, marking a value as volatile prevented >> any caching, etc... Is this wrong? > > No, a mutex doesn't affect the cache (other than side effects) - the > mutex doesn't know what area of memory (variables) it is locking. > It's only there to assure that nooneelse enters the critical section > at the same time. >
You're right, of course. I was confusing cache flushing with simple memory barriers (which, I believe, is what a mutex provides). > Marking a variable as 'volatile' means that it's read from memory > every time it is accessed (the compiler won't attempt to read it into > a register). The idea is that someone else (another thread or > hardware) might modify the value. > > 'volatile' an be used in some cases instead of a lock, for example if > one thread writes a bool (to indicate some event) and another thread > only reads that value. > Yep. It turns out that whenever I write some code using a volatile to avoid synchronizing, I invariably end up replacing it with a mutex protected block because a volatile write is not a memory barrier. Usually, it's some variation of this pseudo code: volatile bool isValid = 0 int i = 0 // in thread 1 acquire mutex i = 42 isValid = true release mutex // in thread 2 if (isValid) use i This doesn't work because setting i and isValid inside the critical section may be reordered. Do I have this right? Cory _______________________________________________ osg-users mailing list osg-users@lists.openscenegraph.org http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org