Boost logo

Boost :

From: Jason Stewart (jstewart_at_[hidden])
Date: 2002-08-07 10:19:40


I saw a technique in C/C++ User Journal, August 2000 by Pete Becker that
had a good solution. Basically, you check the pointer if it is not null
then the expensive_data has been initialized. If it is null then you grab
the mutex and check it again. This second check allows you to make sure
that someone else did not beat you too the initialization.

class something
{
public:
        const expensive_data& get_expensive()
        {
                if (m_expensive.get())
                {
                        boost::Lock lock(m_mutex);
                        if (m_expensive.get())
                        {
                                make_expensive_data;
                        }
                }
                return *m_expensive;
        }
private:
        boost::mutex m_mutex
        std::auto_ptr<expensive_data> m_expensive;
};

This might do what you want because it avoids locking the mutex after the
object has been safely initialized. Apologies to Mr. Becker if I
misrepresented this. Also, I have not really looked at the boost threads so
I don't know if I implemented the locking correctly.

Jason Stewart


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