What exactly shared means?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 2 12:32:51 PST 2015


On 1/2/15 2:47 PM, John Colvin wrote:

>
> 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.

There is nothing special about __gshared other than where it is put.

Real simple test:

__gshared int x;

void main()
{
    int xlocal;
    int *xp = (rand() % 2) ? &x; &xlocal;

    *xp = 5;
}

tell me how the compiler can possibly know anything about what type of 
data xp points at?

But with shared, the type itself carries the hint that the data is 
shared between threads. At this point, this guarantees nothing in terms 
of races and ordering, which is why shared is so useless. In fact the 
only useful aspect of shared is that data not marked as shared is 
guaranteed thread local.

> 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".

Use __gshared for accessing C globals, and otherwise only if you know 
what you are doing. There are many aspects of D that make assumptions 
based on whether a type is shared or not.

-Steve


More information about the Digitalmars-d-learn mailing list