Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2005-01-18 06:51:26


Stefan Slapeta wrote:
> Roland Schwarz wrote:
>
> [...]
>
>> The broader question is:
>> Can local static objects ever be made thread safe? Or should they be
>> avoided at all in MT aware
>> code?
>>
>
> 1) No
> 2) Yes!!

Local static objects can be made safe by the compiler. The new cxx64 API
requires it.

They can also be made safe by using one of the following two approaches
(pseudocode):

1.

mutex m = MUTEX_INITIALIZER;

void f()
{
    mutex_lock(&m);
    static X x;
    mutex_unlock(&m);

    // use x
}

2.

X & instance()
{
    static X x;
    return x;
}

void f()
{
    call_once( instance );
    X /*const*/ & x = instance();
    // use x
}


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