Boost logo

Boost :

From: Andrey Semashev (andysem_at_[hidden])
Date: 2007-02-05 16:55:24


Hello Fabien,

Tuesday, February 6, 2007, 12:31:47 AM, you wrote:

> 2007/2/5, Andrey Semashev <andysem_at_[hidden]>:
>>
>> I guess there should have been only "scoped_lock
>> second_lock(m_mutex2)" and no "scoped_lock first_lock(m_mutex1)".
>> Still, m_mutex2 has to be initialized somewhere and I see no other way
>> for it than to be global, in namespace scope. But once again, I'm not
>> sure even this is actually safe since it's dynamic initialization
>> which apparently may be done concurrently.

> You're perfectly right on this issue: only the second_lock is necessary, and
> pInstance must also be volatile (I never write such code myself, I always
> used Loki implementation when I need a singleton). As for instanciation,
> the standard ensure that a local static variable will only be initialized
> once, before entrance to the block scope. How this is handled in
> multi-thread program? I guess it's depend on your threaded platform. As
> for where the mutexes is defined... Well, that's also depends on the class
> policy (and what's the mutex implementation permits).

The problem is that the current Standard is not aware of threading at
all. And the compiler follows it, making no effort to synchronize
static variables initialization. So indeed, the local static variable
is initialized once in a single-thread application. In MT you're on
your own. You get the desired behavior only if you manage to protect
the static variable initialization from being done in many threads
simultaneously.

> Unless you can ensure that the private variable will not be necessary
> anytime before it's initialization (for example, by a static object inside
> another module), I'm still thinking that the local static variable is safer
> than a class static variable.

I'm not quite sure for my case.

-- 
Best regards,
 Andrey                            mailto:andysem_at_[hidden]

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk