Boost logo

Boost Users :

From: Mattias Brändström (thebrasse_at_[hidden])
Date: 2006-09-07 08:38:12


Hello!

I have a small class that I would like to get some feedback on. If you
have the time. =)

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. This is my
intitial implementation of such a class:

#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>

template <typename T>
class LockPointer
{
public:

   class LockProxy
   {
   public:
     LockProxy(boost::shared_ptr<T> p,
               boost::shared_ptr<boost::recursive_mutex> mutex)
       : p_(p), lock_(new boost::recursive_mutex::scoped_lock(*mutex))
     {
     }

     boost::shared_ptr<T> operator->()
     {
       return p_;
     }

   private:
     boost::shared_ptr<T> p_;
     boost::shared_ptr<boost::recursive_mutex::scoped_lock> lock_;
   };

   LockPointer(boost::shared_ptr<T> o)
     : p_(o), mutex_(new boost::recursive_mutex())
   {
   }

   LockProxy operator->()
   {
     return LockProxy(p_, mutex_);
   }

private:
   boost::shared_ptr<T> p_;
   boost::shared_ptr<boost::recursive_mutex> mutex_;
};

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)?

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?

Regards,
Mattias


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