Threads, shread and TLS
Steven Schveighoffer
schveiguy at yahoo.com
Fri Jan 7 06:37:00 PST 2011
On Fri, 07 Jan 2011 09:24:18 -0500, Adam Conner-Sax
<adam_conner_sax at yahoo.com> wrote:
> So, I thought I sort of understood "shared" and now I think I don't.
>
> If I have a class:
>
> class foo {
> int x;
> static int y;
> shared static int z;
>
> }
>
> So x is one instance per class and is thread-local?
> y is one instance per thread?
> z is one instance per application, i.e., global?
Yes to all
>
> If that's true (and I realize it might not be), and I want to initialize
> these
> variables in constructors, how does that work?
>
> I think
>
> class foo {
> ...(as before)
>
> this() { x = 2; } // ok
>
> static this() { y = 3; } // is this called once per thread?
>
> shared static this() { z = 3;} // also, okay, called before main
> }
>
> but I don't understand what happens with threads and the "static this"
> constructor. How/when are the thread-local copies constructed? How do
> you
> initialize/construct the thread-local static data?
static this() is run upon thread creation (and once at the beginning of
the program for the main thread), and static ~this() is run when a thread
is destroyed.
All static this() and shared static this() functions are assembled by the
runtime into an array of constructors, built in the correct order based on
import dependencies. So each time a thread starts, it simply goes through
an array and calls each function.
-Steve
More information about the Digitalmars-d-learn
mailing list