Boost logo

Boost Users :

From: Sebastian Redl (sebastian.redl_at_[hidden])
Date: 2006-09-07 11:40:44


On Thu, September 7, 2006 8:38 am, Mattias Brändström wrote:
> What I would like to do is to protect an instance of some class T with a
> mutex. It seems to me that I would be able to do this with a smart pointer
> that returns a proxy class, from operator->(), that locks a mutex in its
> constructor and unlocks it in its destrcutor.

I've played with this thought several times in the past. In the end, what
made me never implement it is the fact that it locks and unlocks the mutex
for every single operation on the class. If you call more than one
operation in sequence, that's not exactly efficient.
That said, for classes that have only operations which you usually don't
call in sequence, the pointer is quite useful. I have just one change:
there is no reason to allocate the lock dynamically.

> class LockProxy {
> public:
> LockProxy(boost::shared_ptr<T> p,
> boost::shared_ptr<boost::recursive_mutex> mutex)
> : p_(p), lock_(*mutex)
> {
> }
>
>
> const boost::shared_ptr<T> &operator->()
> {
> return p_; }
>
>
> private:
> boost::shared_ptr<T> p_;
> boost::recursive_mutex::scoped_lock lock_;
> };

I've also changed the return type of operator ->. There's no need to
create a copy of the shared_ptr.

> What do you think? Would this work? Would this be equivalent to locking
> a member mutex in each method of T (as long as all calls to an instance of
> T is invoked via the same LockPointer)?

I'm not entirely sure when the temporary will be destroyed, but if I
remember D&E correctly, then it will work.

> For some reason this is the kind of thing I would expect to find in
> boost, but I have not been able to. Have I missed some part of boost that I
> should know about?

No, there is no such thing in Boost. The reason is probably the limited
set of use cases for the pointer.

Sebastian Redl


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net