Boost logo

Boost :

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


Hello Steven,

Tuesday, February 6, 2007, 12:10:17 AM, you wrote:

> AMDG

> Andrey Semashev <andysem <at> mail.ru> writes:

>> I guess the only way to safely initialize a static local variable is
>> through some call_once concept implementation. The problem in my case
>> is that I'd like the library to be as light as possible and as fast as
>> possible, so I can't make use of Boost.Thread for now.

> I believe that volatile works just as well here
> as it does for m_StatesInfo.

> template<class Dispatcher>
> struct static_event_dispatcher {
> static volatile bool initialized;
> //Dispatcher must have a trivial default constructor
> static Dispatcher dispatcher;
> static Dispatcher& value() {
> if(!initialized) {
> const_cast<volatile Dispatcher&>(dispatcher).init();
> initialized = true;
> }
> return(dispatcher);
> }
> };

> template<class Dispatcher>
> static volatile bool
> static_event_dispatcher<Dispatcher>::initialized = 0;
> template<class Dispatcher>
> static Dispatcher static_event_dispatcher<Dispatcher>::dispatcher;

Well, the dispatcher is quite safe even if it's initialized more than
once and even concurrently. Being a namespace-scope object is quite
sufficient for it. But state names, which are std::strings, are quite
fragile in this way. And unfortunately volatile flags won't help here.

-- 
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