www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Does __gshared have shared semantics?

reply "Mike Franklin" <none none.com> writes:
In other words, is 'shared __gshared' redundant?
Jun 13 2014
next sibling parent "Kapps" <opantm2+spam gmail.com> writes:
On Saturday, 14 June 2014 at 01:24:05 UTC, Mike Franklin wrote:
 In other words, is 'shared __gshared' redundant?
All __gshared does is makes the variable not go into thread-local storage, nothing more. Shared does this, as well as modify the type to be shared(T) instead of just T. So yes, it's redundant.
Jun 13 2014
prev sibling parent Jonathan M Davis via Digitalmars-d-learn writes:
On Sat, 14 Jun 2014 01:24:03 +0000
Mike Franklin via Digitalmars-d-learn
<digitalmars-d-learn 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
Jun 14 2014