On Friday, 2 January 2015 at 13:14:14 UTC, Jonathan M Davis via
Digitalmars-d-learn wrote:
Objects in D default to being thread-local. __gshared and
shared both make
it so that they're not thread-local. __gshared does it without
actually
changing the type, making it easier to use but also dangerous
to use,
because it makes it easy to violate the compiler's guarantees,
because it'll
treat it like a thread-local variable with regards to
optimizations and
whatnot.
I'm pretty sure that's not true. __gshared corresponds to C-style
globals, which are *not* assumed to be thread-local (see below).
shared does not add any more synchronization or automatic
mutex-locking or
anything like that than __gshared does (IIRC, there is some
talk in TDPL
about shared adding memory barriers - which __gshared wouldn't
do - but that
hasn't been implemented and probably never would be, because it
would be too
expensive with regards to efficiency). However, unlike
__gshared, shared
_does_ alter the type of the variable, so the compiler will
treat it
differently. That way, it won't do stuff like optimize code
under the
assumption that the object is thread-local like it can do with
non-shared
objects.
Are you sure about all this optimisation stuff? I had (perhaps
wrongly) assumed that __gshared and shared variables in D
guaranteed Sequential Consistency for Data Race Free (SCDRF) and
nothing more, just like all normal variables in C, C++ and Java.
Thread-local variables (i.e. everything else in D ) could in
theory be loosened up to allow some *extra* optimisations that
C/C++/Java etc. don't normally support (because they would risk
violating SCDRF), but I don't know how much of this is taken
advantage of currently.
If I'm correct, then the advice to users would be "Use __gshared
and pretend you're writing C/C++/Java, or use shared and do
exactly the same but with type-system support for your
convenience/frustration".