[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c++

Thread safety problems with function scope static variables vs class static private members

Hicham Mouline

12/18/2008 5:42:00 PM

I have a function f that is called from multiple threads
I have the choice between setting a const int array as a static local in f()

void C::f() {
static const int keys[] = { 0, ...., 15 };
}

or as a private member of C

class C {
private:
static const int keys[] ;
};
const int C::keys[] = { 0....15 };



1 In theory?
Is there a risk that keys are initialized badly because keys is a static
local variable of f (keys init'ed only first time exec enters f)
while no risk when keys is a static member of C (because keys is init'ed
before runtime passes through main even)?
I know c++03 says nothing about threads. Can one still infer anything from
it?

2 In practise, (msvc, g++, intel....)
Do these make sure keys init as function local is ok, and as a member of C
also?

regards,


1 Answer

James Kanze

12/19/2008 8:10:00 PM

0

On Dec 19, 12:49 pm, Juha Nieminen <nos...@thanks.invalid> wrote:
> James Kanze wrote:
> > On Dec 18, 6:41 pm, "Hicham Mouline" <hic...@mouline.org> wrote:
> >> void C::f() {
> >> static const int keys[] = { 0, ...., 15 };
> >> }

> > No. In both cases, you have static initialization, which is
> > guaranteed to occur before anything else.

> I thought that a static inside a function is initialized the
> first time the function is called?

The standard explicitly says otherwise: "Objects of POD types
with static storage duration initialized with constant
expressions shall be initialized before any dynamic
initialization takes place." (§3.6.2/1).

In fact, in this case, the word static means what it says; such
variables are initialized statically, not dynamically.

> The above function might not be problematic with regard to
> thread safety, but what about something like this:

> void foo()
> {
> static SomeClass object;
> ...
> }

It depends on SomeClass, obviously. Does SomeClass use static
or dynamic initialization?

> Suppose that 'foo()' may be called from more than one thread.
> Can it happen that 'object' is constructed more than once?

Probably. I don't know what the next version of the standard
will say about it, but in current implementations, it's
undefined behavior to enter such a function from several
different threads without some sort of external synchronization.

But what does this have to do with static initialization?

--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34