Shared

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu May 16 17:29:25 UTC 2019


On Thursday, May 16, 2019 11:11:19 AM MDT Simen Kjærås via Digitalmars-d 
wrote:
> On Thursday, 16 May 2019 at 15:47:37 UTC, Dominikus Dittes
>
> Scherkl wrote:
> > On Thursday, 16 May 2019 at 11:15:13 UTC, Jonathan M Davis
> >
> > wrote:
> >> [...] that is assuming that it's not possible to have any
> >> other references to the same data, which would be too
> >> restrictive to be useful. Having multiple references to the
> >> same data is a core concept of sharing data across threads.
> >
> > Hm. I don't understand the necessity of this. If I have a
> > shared symbol x,
> > this same symbol can be used in different threads, no? I can't
> > see why multiple threads need to have different references to
> > the same data. They just can use the same reference.
>
> Well, no. The reference is the part that gets copied around. It's
> the address of the shared object. When you do 'auto ref2 =
> ref1;', you're creating a new reference to an already existing
> object, but leaving the object itself unchanged.
>
> If more than one thread can access the same object, that means
> they each have a copy of the reference*. In the same way, when
> you call a function with a class argument, that function receives
> a copy of the reference (but not the object). Clearly then, the
> ability to create multiple references to the same object must be
> possible without breaking shared.

Exactly. And since everything in D is thread-local by default, it's usually
the case that a variable only exists on one thread. shared changes that if
the variable is static, but otherwise, you're just passing around a pointer
or reference to shared objects within thread-local objects. So, while  you
might have a pointer to shared data contained by a variable with the same
name on multiple threads, because that variable is thread-local, it's
different on different threads. e.g.

struct S
{
    int i;
    shared Foo* foo;
}

// Every thread will have it's own variable for this
S s;

- Jonathan M Davis






More information about the Digitalmars-d mailing list