What exactly shared means?
John Colvin via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jan 2 13:05:59 PST 2015
On Friday, 2 January 2015 at 20:32:51 UTC, Steven Schveighoffer
wrote:
> 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
Perhaps a more precise statement of affairs would be this:
All variables/data are SC-DRF with the exception of static
variables and globals, which are thread-local. `shared` exists
only to express via the type-system the necessity of thread-safe
usage, without prescribing or implementing said usage.
Hmm. I went in to writing that thinking "shared isn't so bad".
Now I've thought about it, it is pretty damn useless. What's the
point of knowing that data is shared without knowing how to
safely use it? I guess it protects against completely naive usage.
Couldn't we have thread-safe access encapsulated within types
a-la std::atomic?
More information about the Digitalmars-d-learn
mailing list