Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2003-09-27 19:57:50


Thanks Daniel!

On Sep 27, 2003, at 7:01 PM, Daniel Wallin wrote:

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

Yeah, the copy ctor worries me. You've got the same thread trying to
lock what it already owns. If the mutex is recursive that would be ok
though. Maybe that's the ticket. I'll think about that some more.
Thanks!

> In that case, couldn't you allocate the scoped_lock dynamically and
> move it
> when copying?

I was really hoping to avoid heap allocation on this one.

-Howard


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