Does __gshared have shared semantics?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 14 02:36:57 PDT 2014


On Sat, 14 Jun 2014 01:24:03 +0000
Mike Franklin via Digitalmars-d-learn
<digitalmars-d-learn at puremagic.com> wrote:

> In other words, is 'shared __gshared' redundant?

Redundant? Not exactly.

__gshared makes it so that the variable is treated like a C variable - it's
not in TLS - but its _type_ is still considered to be thread-local by D. So,
you get no protection from the type system when using a  __gshared variable.
It'll treat it like a normal, TLS variable. So, you need to be very careful
when using __gshared.

shared on the other hand _is_ treated differently by the type system. Like
__gshared, it's not in TLS, but that fact is then embedded in its type, so the
compiler won't make any optimizations based on TLS for a shared variable, and
it will at least partially protect you agains using it in contexts which are
guaranteed to be wrong for shared. e.g with the current version of the
compiler in git, this code

shared int i;

void main()
{
    ++i;
}

produces this error

q.d(5): Deprecation: Read-modify-write operations are not allowed for shared
variables. Use core.atomic.atomicOp!"+="(i, 1) instead.

whereas if it were __gshared, it wouldn't complain at all.

So, when marking a variable both shared and __gshared, the __gshared is kind
of pointless, since shared essentially indicates everything that __gshared
does plus more. However, the compiler will give you an error message if you
try (at least with the current git master anyway - I'm not sure what it did
with 2.065, since I don't have it installed at the moment), so there really
isn't much reason to worry about what it would actually do if it compiled.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list