[dmd-concurrency] shared arrays

Andrei Alexandrescu andrei at erdani.com
Thu Jan 14 15:07:26 PST 2010


Steve Schveighoffer wrote:
> ----- Original Message ----
>> From: Andrei Alexandrescu <andrei at erdani.com> To: Discuss the
>> concurrency model(s) for D <dmd-concurrency at puremagic.com> Sent:
>> Thu, January 14, 2010 3:57:12 PM Subject: Re: [dmd-concurrency]
>> shared arrays
>> 
>> I understand. The thing is, shared means "can be changed by another
>> thread at any time" so I think the behavior you mention is 100%
>> expectable.
>> 
>> If you want to do away with shared, you need to add
>> synchronization.
>> 
>> I agree that the existence of multibyte characters constitute an
>> argument in favor of disabling certain operation. But as long as I
>> can mess up a string in one thread, I will be able to mess it up in
>> several.
> 
> I just don't understand the dual standard.
> 
> Let's forget about long, and talk about arrays or any struct larger
> than a single int (but whose individual pieces are at most int size).
> Why is it ok to copy a partially-modified string which is considered
> a whole unit, but it is not OK to copy a partially modified struct
> with two ints in it?  It's not like you can tear the ints, setting
> each is atomic.  It looks like the same issue to me, but the compiler
> refuses to compile one and happily accepts the other.

You are right. Let's first consider:

struct A { int a, b; }

shared A x, y;
x = y;          // yay or nay?

I think this should be allowed. This is because A makes no attempt to 
protect its data by e.g. defining a copy constructor. Anyone could 
modify a, b in any way - so why not different threads?

Case two. Consider:

struct B {
     int a, b;
     this(this) {
        ...
     }
}

In this case code could still modify a and b arbitrarily, but the type 
signals that it wants to do something special upon copying. I'd argue 
that shared Bs should not be copyable. To become copyable, they should 
do this:

struct B {
     int a, b;
     this(this) {
        ...
     }
     this(this) shared {
        ...
     }
}

(I'm not worried about code duplication as the body is different more 
often than not.)

Finally, consider this case:

struct C {
     int a;
     long b;
     ...
}

I'd argue that shared objects of this type shouldn't be copyable. What 
if it adds a shared constructor?

struct C {
     int a;
     long b;
     this(this) shared { ... }
}

Unfortunately, this(this) is called after the bits have been copied, so 
if there was any tearing, it already happened. I don't know how we can 
solve this.


Andrei


More information about the dmd-concurrency mailing list