Thread overview
shared attrribute
Mar 14, 2013
Jack Applegame
Mar 14, 2013
John Colvin
Mar 15, 2013
Jack Applegame
March 14, 2013
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;
}

March 14, 2013
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".
March 15, 2013
Thanks. I's much more clear now.