shared attribute

Jonathan M Davis jmdavisProg at gmx.com
Sun May 13 06:04:47 PDT 2012


On Sunday, May 13, 2012 14:35:14 japplegame wrote:
> Very intresting. Next question. :)
> Lets consider this example.
> 
> >import core.thread;
> >import std.stdio;
> >
> >shared char[] s;
> >char[] l = "shared text".dup;
> >
> >void main() {
> >
> >  Thread worker = new Thread(&workerFunc);
> >  worker.start();
> >  Thread.sleep(dur!"seconds"(5)); // after this point worker
> > 
> > thread and its
> > 
> >                                  // local storage most likely
> > 
> > destroyed
> > 
> >  s[2] = 'd';                     // undefined behaviour?
> >
> >}
> >
> >void workerFunc() {
> >
> >   s = cast(shared)l;
> >
> >}

I actually don't know. Because you had to cast to shared, it might be 
undefined, but then again, the compiler might be smart enough to move it into 
non-thread local storage at that point. I don't know exactly what it does. If 
it had been constructed as shared in the first place (which you can't do with a 
string, unfortunately), it wouldn't be an issue at all, but it might be in 
this case. However, while I know the basics of shared, I'm not familiar with 
all of the nitty gritty details, so I can't really answer the question well.

I'd suggest reading the concurrency chapter from TDPL (The D Programming 
Language by Andrei Alexandrescu) if you want all of the concurrency stuff 
explained. It may or may not answer your question (it's been a while since I 
read it). But unlike most of TDPL, that chapter is available for free online 
in case you don't have the book:

http://www.informit.com/articles/article.aspx?p=1609144

The recommended way to deal with concurrency in D is to avoid shared and use 
message passing with std.concurrency (which is what I normally do). So, if you 
can do that in your program rather than using shared, that's recommended 
(though shared, synchronized, and mutexes are definitely there if you _do_ need 
them).

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list