[cpp-threads] static locals
Peter Dimov
pdimov at mmltd.net
Thu Jun 2 00:01:05 BST 2005
Alexander Terekhov wrote:
> decadentplace.org.uk seems to be down. Any comments?
Yep, the archives work, but I'm not getting any posts.
> ---------- Forwarded message ----------
> From: Alexander Terekhov <alexander.terekhov at gmail.com>
> Date: Jun 1, 2005 1:53 PM
> Subject: Re: [cpp-threads] static locals
> To: cpp-threads at decadentplace.org.uk
>
>
> On 6/1/05, Andrei Alexandrescu <andrei at metalanguage.com> wrote:
> [...]
>> 1. There's a clear distinction between statically initialized static
>> data and dynamically initialized static data.
>>
>> 2. In the case of dynamically-initialized static data, the expression
>> that initializes is guaranteed to be executed at runtime before any
>> function in the static data's module is called.
>
> My reading of 6.7/4 is that "early initialization" means "early
> zero-initialization" (see 6.7/4's first statement), not "early
> dynamic initialization". Early zero-initialization and
> initialization with a constant expression (collectively called
> static initialization) aside for a moment, dynamic initialization
> occurs "the first time control passes through its declaration".
No, zero initialization is performed before everything else. Early
initialization may occur if the conditions in 3.6.2/2 allow it.
int f() { return 5; }
int g()
{
static int x = f();
return x;
}
'x' can be early initialized to 5, because f() doesn't have side effects and
returns a constant value.
>> Of course, a compiler could fool you if you could never tell.
>
> "As if", of course.
This optimization is detectable in some situations - see the example in
3.6.2/2 - so it's explicitly allowed. "As if" applies only if you really
could never tell.
To reply to Hans Boehm's post:
> Looking at this again, I agree that this is less clear than I thought,
> and we could probably fix things to require thread-safety.
>
> But consider something like
>
> void f(int my_thread_id) {
> thread_info[my_thread_id] = ...;
> static int master_thread_id = my_thread_id;
>
> ...thread_info[master_thread_id]...
>
> }
>
> It is unlikely that the initialization of master_thread_id would
> be done statically, but I think there's no rule that currently
> prevents it.
(I've added a name to the function)
Taken in isolation, the initialization of master_thread_id definitely cannot
be performed early, because the compiler can't prove that the requirements
of 3.6.2/2 are met.
But if this function is static, and the only calls to it are
static int x = f( 1 ), 1;
static int y = f( 2 ), 2;
at namespace scope, and its address is never taken, then master_thread_id
can be initialized statically to 1 (unless something else in f prevents the
optimization).
More information about the cpp-threads
mailing list