标签:vat end public unlock c++ 做自己 ase class rtu
由于C++编程中,经常用到多线程编程。这样的话就得用到锁,因此就把锁的操作封装到一个类中,实现如下:
#include <pthread.h>
typedef pthread_mutex_t CRITICAL_SECTION;
class LockBase
{
public:
LockBase();
virtual ~LockBase();
virtual void Lock() = 0;
virtual void UnLock() = 0;
};
class DerivedLock : public LockBase
{
public:
DerivedLock();
virtual ~DerivedLock();
virtual void Lock();
virtual void UnLock();
virtual void Destroy();
private:
CRITICAL_SECTION m_cs;
};
class SafeLock
{
public:
SafeLock();
SafeLock(LockBase* pLock);
virtual ~SafeLock();
private:
LockBase *m_pLock;
};
==============================类的实现如下==============================================
LockBase::LockBase()
{
}
LockBase::~LockBase()
{
}
DerivedLock::DerivedLock()
{
pthread_mutex_init(&m_cs, NULL);
}
DerivedLock::~DerivedLock()
{
pthread_mutex_destroy(&m_cs);
}
void DerivedLock::Lock()
{
pthread_mutex_lock(&m_cs);
}
void DerivedLock::UnLock()
{
pthread_mutex_unlock(&m_cs);
}
void DerivedLock::Destroy()
{
pthread_mutex_destroy(&m_cs);
}
SafeLock::SafeLock()
{
m_pLock = NULL;
}
SafeLock::SafeLock(LockBase* pLock)
{
m_pLock = pLock;
if (m_pLock)
{
m_pLock->Lock();
}
}
SafeLock::~SafeLock()
{
if (m_pLock)
{
m_pLock->UnLock();
m_pLock = NULL;
}
}
最后的使用如下:
DerivedLock m_csMosending;
int main()
{
if(1)
{
SafeLock safelock(&m_csMosending);
//做自己所要的操作......
}
return 0;
}
标签:vat end public unlock c++ 做自己 ase class rtu
原文地址:https://www.cnblogs.com/Unclebigdata/p/14862838.html