www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - shared attrribute

reply "Jack Applegame" <japplegame gmail.com> writes:
What does mean attribute shared exactly for non global variables? 
Is it safe to cast to/from shared?

For example, let us assume all data are synchronized properly. Is 
following code safe?

import core.atomic;

class A {
   int value;
}

struct B {
   A node;
}

void main() {
   shared B data;
   A node = new A;
   atomicStore(data, shared B(cast(shared) node));
   ...
   node = atomicLoad(data).node;
}
Mar 14 2013
parent reply "John Colvin" <john.loughran.colvin gmail.com> writes:
On Thursday, 14 March 2013 at 10:39:11 UTC, Jack Applegame wrote:
 What does mean attribute shared exactly for non global 
 variables? Is it safe to cast to/from shared?

 For example, let us assume all data are synchronized properly. 
 Is following code safe?

 import core.atomic;

 class A {
   int value;
 }

 struct B {
   A node;
 }

 void main() {
   shared B data;
   A node = new A;
   atomicStore(data, shared B(cast(shared) node));
   ...
   node = atomicLoad(data).node;
 }
Without knowing what threads are running and which have access to which variables, it's hard to say much. The store is safe as long as no one touches "node" during the construction of the temporary "shared B". The load of "data" is safe, but the access of "node" is only safe if you can guarantee that no-one else can touch it during the read. Shared is (in it's current form) a compiler enforced annotation and not much more. It is merely a way of saying "This data may be accessed from other threads, be careful".
Mar 14 2013
parent "Jack Applegame" <japplegame gmail.com> writes:
Thanks. I's much more clear now.
Mar 14 2013