[Mono-devel-list] Thread safety of readonly data members?
cwitty at newtonlabs.com
Wed Feb 18 23:11:24 EST 2004
On Wed, 2004-02-18 at 16:18, Jonathan Pryor wrote:
> On Wed, 2004-02-18 at 18:09, Carl Witty wrote:
> > > I forgot to mention this, but in C++ the static member would also need
> > > to be declared as "volatile" for double-checked locking to properly
> > > work, IIRC.
> > Are you sure this works? This would require that compilers for some
> > platforms (at least for Alpha) put memory-barrier instructions around
> > accesses of volatile variables; I'd check to make sure that this really
> > happens before relying on double-checked locking with that compiler.
> I am reasonably sure this works. At least, this is generally what most
> books on threading that I've read have recommended.
> Furthermore, the C++ standard I have, in section 1.9 (Program execution)
> has the following statements:
> 7. Accessing an object designated by a volatile lvalue (3.10),
> modifying an object, calling a library I/O function, or calling
> a function that does any of these operations are all side
> effects, which are changes in the state of the execution
> environment... At certain specified points in the execution
> sequence called sequence points, all side effects of previous
> evaluations shall be complete and no side effects of subsequent
> evaluations shall have taken place. [Sequence points occur
> after every complete statement.]
> 11. The least requirements on a conforming implementation are:
> - At sequence points, volatile objects are stable in the
> sense that previous evaluations are complete and
> subsequent evaluations have not yet occurred.
> This would imply to me that my understanding is correct, but I haven't
> written a compiler, so I could be wrong.
But according to section 1.9, paragraphs 1 and 6, the compiler is
allowed to move non-volatile reads and writes up or down past volatile
reads or writes. I don't think paragraph 11 is relevant; we're
discussing volatile pointers to non-volatile objects, not volatile
And no amount of "volatile" will help, unless the compiler surrounds
accesses to volatiles with memory barriers (a memory barrier is a
special instruction which guarantees that modifications to memory made
by one processor are visible to another processor). My guess is that
most compilers do not automatically emit memory barriers for volatile
accesses (for instance, in a quick check through the Alpha code
generator in the gcc 2.95.3 source tree I happened to have lying about,
I didn't see any evidence that it used memory barriers for anything
besides synchronizing data and instruction caches on a single
I recommend reading:
More information about the Mono-devel-list