Assignment of shared values

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Thu Aug 7 09:44:36 PDT 2014


On 8/7/14, 5:25 AM, Dicebot wrote:
> On Wednesday, 6 August 2014 at 23:01:11 UTC, Andrei Alexandrescu wrote:
>> Somewhat sadly, this code does compile:
>>
>> shared S s1, s2;
>> s1 = s2;
>
> I have no idea what semantics this may have from just reading the
> snippet.

Well right now it just copies field by field, non-atomically.

> IMHO killing it will be a good thing and totally in line with
> your comments about shared you have made during DConf conversations.

Yah. The basic intent behind "shared" is to disallow unwitting racy 
code, and allow users to define robust shared abstractions.

Consider this code at top level:

struct S {
   private long a, b, c;
   ...
}
shared S g_theS;

All threads will "see" the same g_theS. The intent of "shared" is to 
disallow racy/wrong use of g_theS across threads. However, assigning 
g_theS is by default allowed and does something definitely racy.

So I think we should do the following:

* if S.sizeof <= size_t.sizeof, generate atomic assignment automatically 
for shared values.

* if S.sizeof == 2 * size_t.sizeof, generate special 128-bit atomic 
assignment for shared values on 64-bit systems, and 64-bit atomic 
assignment on 32-bit systems.

* In all other cases, reject code during compilation and require an 
opAssign for shared values.

This will break code. It may even break correct code (benign races or 
code that uses external locking). On the other hand, it seems like the 
right thing to do by the intended semantics of "shared".

>> However, assigning Variant objects holding such structs does not
>> compile, which in turn leads to the reported bug in std.concurrency.
>> Now it seems to me that the only way is to adapt Variant to allow such
>> assignments, otherwise we'd be breaking existing code. Thoughts
>> appreciated.
>
> I think biggest std.concurrency problem is that people try to use
> `shared` as poor replacement to `unique`/`isolated` and this is not what
> it is supposed to mean. Making `Unique` work with std.concurrency can be
> a good direction to make things much less confusing.

Agreed.


Andrei



More information about the Digitalmars-d mailing list