Boost logo

Boost Users :

From: Mattias Brändström (thebrasse_at_[hidden])
Date: 2006-06-30 06:26:57


Hello!

I have a small class to show you and perhaps get some comments on:

<code>
#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_;
};
</code>

The purpose of this class is to lock a mutex before each method call on
an object of class T, and unlock the mutex when that call returns. It
seems that this would be something that one would like to have in some
cases. Maybe so many cases that it might be part of boost somewhere? I
haven't found any library in boost that does this. Is there one?

I haven't done anything like this before so it would be nice if anyone
here could make some comments on the code. Will it do what I think it
does or will it blow up in my face? :-)

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