mirror of
https://github.com/Xahau/xahaud.git
synced 2025-12-06 17:27:52 +00:00
Turns out there is an elegant way to do it.
This commit is contained in:
65
ScopedLock.h
65
ScopedLock.h
@@ -2,68 +2,25 @@
|
|||||||
#define __SCOPEDLOCKHOLDER__
|
#define __SCOPEDLOCKHOLDER__
|
||||||
|
|
||||||
#include "boost/thread/recursive_mutex.hpp"
|
#include "boost/thread/recursive_mutex.hpp"
|
||||||
|
#include "boost/interprocess/sync/scoped_lock.hpp"
|
||||||
// This is a returnable lock holder.
|
#include "boost/shared_ptr.hpp"
|
||||||
// I don't know why Boost doesn't provide a good way to do this.
|
|
||||||
|
|
||||||
class ScopedLock
|
class ScopedLock
|
||||||
{
|
{
|
||||||
private:
|
protected:
|
||||||
boost::recursive_mutex *mMutex; // parent object has greater scope, so guaranteed valid
|
mutable boost::shared_ptr<boost::interprocess::scoped_lock<boost::recursive_mutex> > mHolder;
|
||||||
mutable bool mValid;
|
|
||||||
|
|
||||||
ScopedLock(); // no implementation
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
ScopedLock(boost::recursive_mutex &mutex) : mMutex(&mutex), mValid(true)
|
ScopedLock(boost::recursive_mutex &mutex) :
|
||||||
|
mHolder(new boost::interprocess::scoped_lock<boost::recursive_mutex>(mutex))
|
||||||
|
{ ; }
|
||||||
|
void lock(void) const
|
||||||
{
|
{
|
||||||
mMutex->lock();
|
mHolder->lock();
|
||||||
}
|
}
|
||||||
|
void unlock(void) const
|
||||||
~ScopedLock()
|
|
||||||
{
|
{
|
||||||
if(mValid) mMutex->unlock();
|
mHolder->unlock();
|
||||||
}
|
|
||||||
|
|
||||||
ScopedLock(const ScopedLock &sl)
|
|
||||||
{
|
|
||||||
mMutex=sl.mMutex;
|
|
||||||
if(sl.mValid)
|
|
||||||
{
|
|
||||||
mValid=true;
|
|
||||||
sl.mValid=false;
|
|
||||||
}
|
|
||||||
else mValid=false;
|
|
||||||
}
|
|
||||||
|
|
||||||
ScopedLock &operator=(const ScopedLock &sl)
|
|
||||||
{ // we inherit any lock the other class member had
|
|
||||||
if(mMutex!=sl.mMutex)
|
|
||||||
{
|
|
||||||
if(mValid) mMutex->unlock();
|
|
||||||
mMutex=sl.mMutex;
|
|
||||||
mMutex->lock();
|
|
||||||
mValid=true;
|
|
||||||
}
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
void unlock(void)
|
|
||||||
{
|
|
||||||
if(mValid)
|
|
||||||
{
|
|
||||||
mMutex->unlock();
|
|
||||||
mValid=false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void lock(void)
|
|
||||||
{
|
|
||||||
if(mValid)
|
|
||||||
{
|
|
||||||
mMutex->lock();
|
|
||||||
mValid=true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user