|
Boost : |
From: Daniel Wallin (dalwan01_at_[hidden])
Date: 2003-09-27 18:01:29
At 23:15 2003-09-27, Howard Hinnant wrote:
>Hello,
>
>I'm looking for design guidelines for using boost::threads along with
>the singleton pattern. I'm not concerned with the threadsafe
>construction of the singleton. Rather I want to return a smart pointer
>to the singleton that also acts as a lock so that only one thread at a
>time can access the singleton.
><snip>
>Is it just me, or is this much harder (and more expensive) than it needs
>to be? Am I missing some simpler, lighter weight solution?
Maybe I haven't fully understood the problem, but wouldn't this work:
template<class T>
class locked_ptr
{
public:
locked_ptr(T* p, boost::mutex& m)
: m_p(p)
, m_mutex(m)
, m_lock(m)
{}
locked_ptr(const locked_ptr& x)
: m_p(x.m_p)
, m_mutex(x.m_mutex)
, m_lock(x.m_mutex)
{}
T* operator->() const
{
return m_p;
}
T& operator*() const
{
return *m_p;
}
private:
T* m_p;
boost::mutex& m_mutex;
boost::mutex::scoped_lock m_lock;
void operator=(const locked_ptr&);
};
locked_ptr<X> singleton()
{
static boost::mutex m;
static X x;
return locked_ptr<X>(&x, m);
}
I guess it might not be efficient to lock every time the handle is copied
though.
In that case, couldn't you allocate the scoped_lock dynamically and move it
when copying?
--- Daniel Wallin
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk