Boost logo

Boost :

From: Fabien Niñoles (fabien.ninoles_at_[hidden])
Date: 2007-02-05 15:29:08


2007/2/5, Andreas Huber <ahd6974-spamgroupstrap_at_[hidden]>:
>
> Fabien Niñoles wrote:
> > Probably you should put it has a static local variable inside a
> > protected function, like this:
> >
> > //! The method returns a reference to the only dispatcher instance
> >
> > static state_dispatcher const& get()
> > {
> > static state_dispatcher instance;
> > return instance;
> > }
>
> In a multithreaded app this might work on some platforms, on others it
> doesn't:
>
> Quote from http://msdn2.microsoft.com/en-us/library/s1sb61xd.aspx:
> "Assigning to a static local variable is not thread safe and is not
> recommended as a programming practice."
>
> Although this isn't very concise wording (IIRC, the standard says that
> it should work for literals assigned to PODs) it seems clear that it
> won't work for non-PODs...

For assignation, sure, but I don't see any in my code... However, if that's
bother, I think then only something like Loki Singleton pattern will do.
You then need a double lock for accessing it correctly, something like this:

static state_dispatcher const& get()
{
    static state_dispatcher* pInstance;
    scoped_lock first_lock(m_mutex1)
    if (!pInstance)
    {
       scoped_lock second_lock(m_mutex2);
       if (!pInstance)
       {
          pInstance = new state_dispatcher;
       }
    }
    return *pInstance;
}

The problem is now one of performance, which Loki handle by making the
scoped_lock class a template class policy.


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