thread-safe local static variable initialization

Jonathan Schilling jls at sco.com
Mon Jun 7 23:54:00 UTC 1999


> From: Jim Dehnert <dehnert at baalbek.engr.sgi.com>
> 
> > [Mike Ball said]
> > As far as I can tell, the language says that the automatic blocking
> > issue isn't a valid approach.  It says what has to happen, and
> > it isn't that.
> 
> Are you referring to the statement in 6.7 that "If control re-enters
> the declaration (recursively) while the object is being initialized,
> the behavior is undefined?"  

No, 6.7 /4 is referring to a single-threaded program where the static
local variable initialization expression calls the function containing
the static local.

The standard is mute on multiple threads of control in general, so 
there is no requirement in the language to support what I'm talking
about. But as a practical matter compilers have to do it (Watcom gave
a paper on their approach during the standardization process, if I
remember).  This example using UI/SVR4 threads will usually show whether 
a compiler does it or not: 

thr5.C:
// static local initialization and threads

#include <stdlib.h>
#define EXIT(a) exit(a)
#define THR_EXIT() thr_exit(0)

#include <thread.h>

int init_count = 0;
int start_count = 0;

int init()
{
	::thr_yield();
	return ++init_count;
}

void* start(void* s)
{
	start_count++;
	static int i = init();
	if (i != 1) EXIT(5);
	THR_EXIT();
	return 0;
}
		
int main()
{
	thread_t t1, t2;
	if (::thr_create(0, 0, start, 0, 0L, &t1) != 0) EXIT(1);
	if (::thr_create(0, 0, start, 0, 0L, &t2) != 0) EXIT(2);
	if (::thr_join(t1, 0, 0) != 0) EXIT(3);
	if (::thr_join(t2, 0, 0) != 0) EXIT(4);
	if (start_count != 2)
		EXIT(6);
	if (init_count != 1)
		EXIT(7);
	THR_EXIT();
}

When compiled with CC -Kthread thr5.C on UnixWare 7, for instance,
it passes by returning 0.  When compiled with CC -mt thr5.C on
Solaris/x86 C++ 4.2 (sorry don't have the latest version!), it
fails by returning 5.

If there's a way of supporting this without affecting the ABI,
I'll be happy to be enlightened :)

Jonathan Schilling		SCO, Inc.		jls at sco.com




More information about the cxx-abi-dev mailing list