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<Tp,
boost::shared_ptr<boost::recursive_mutexmutex)
: p_(p), lock_(new boost::recursive_mutex::scoped_lock(*mutex))
{
}
boost::shared_ptr<Toperator->()
{
return p_;
}
private:
boost::shared_ptr<Tp_;
boost::shared_ptr<boost::recursive_mutex::scoped_l ocklock_;
};
LockPointer(boost::shared_ptr<To)
: p_(o), mutex_(new boost::recursive_mutex())
{
}
LockProxy operator->()
{
return LockProxy(p_, mutex_);
}
private:
boost::shared_ptr<Tp_;
boost::shared_ptr<boost::recursive_mutexmutex_;
};
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