Where are the semantics of shared defined?

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Sat Aug 15 02:30:46 PDT 2015


On Friday, 14 August 2015 at 18:52:42 UTC, rsw0x wrote:
> On Friday, 14 August 2015 at 12:43:26 UTC, thedeemon wrote:
>> Anrei's TDPL book spent a lot of words on shared (and this 
>> book had kind-of-a-spec reputation), but I don't know how much 
>> of it is relevant now.
>
> I know for a fact that a lot of the things related to shared in 
> TDPL aren't implemented or considered anymore.
>
> Is it really not documented anywhere of what shared actually 
> does currently?
> This is ridiculous.

There is actually very little in TDPL which has not been 
implemented. Off the top of my head, the only ones that I can 
think of are multiple alias thises, synchronized classes, and 
memory barriers for shared. Now, the alias this issues is really 
the only one that doesn't have to do with shared, so what it 
explains about shared definitely isn't the current situation, but 
on the whole, what TDPL talks about has been implemented, and 
very little of it has changed, though a few things have (e.g. it 
was written before we had "weak" purity). So, you can't 
necessarily take what TDPL says as law, but it's close.

But even with shared, what TDPL says is essentially correct aside 
from the fact that it doesn't have memory barriers, and we don't 
have synchronized classes to help work with shared objects.

Now, as for shared in the spec... I don't know what it says 
without digging through it, but the spec is notoriously sparse in 
the information that it has. The current implementation of shared 
is pretty straightforward though. shared objects are not treated 
as thread-local and won't implicitly convert to or from 
thread-local. There are no memory barriers or any special 
protections for integrity across threads for shared any more than 
a normal variable in C/C++ has such protections. It's just that 
shared variables are actually shared across threads and are 
protected against implicitly converting to or from thread-local. 
The only other protections that shared provides is that some 
non-atomic operations are declared illegal by the compiler, 
forcing you to either use functions in core.atomic or to protect 
the variable with a mutex and cast away shared to operate on it.

On the whole, if you understand how a variable in C/C++/C#/Java 
works, you understand how shared works. It's just that unlike 
C++, normal variables in D are thread-local, and shared is 
protected against interacting with them in a manner which 
violates that, and some non-atomic operations are illegal to 
protect you from shooting yourself in the foot.

So, the spec probably needs more information on shared in it, but 
there really isn't much to put.

- Jonathan M Davis


More information about the Digitalmars-d mailing list