#include ".\opencsp_mutex.h"
unsigned long OPENCSP_UsrMutex::_ulLockCnt(0);
DWORD OPENCSP_UsrMutex::_dwProcessId(0);
OPENCSP_Mutex OPENCSP_UsrMutex::_dscs;
OPENCSP_Mutex::OPENCSP_Mutex() //线程同步
:_sect() //构造函数后加冒号 ,使用初始化成员列表对对象进行初始化
{//初始化一个临界资源对象,来解决同步互斥问题。参数为临界资源对象指针
::InitializeCriticalSection(&_sect);
}
OPENCSP_Mutex::~OPENCSP_Mutex()
{
::DeleteCriticalSection(&_sect);
}
OPENCSP_Mutex::operator LPCRITICAL_SECTION()
{
return (LPCRITICAL_SECTION)&_sect;
}
BOOL OPENCSP_Mutex::lock()
{
::EnterCriticalSection(&_sect);//进入临界区,让每个线程都按顺序地访问变量
return TRUE;
}
BOOL OPENCSP_Mutex::unlock()
{
::LeaveCriticalSection(&_sect);//离开临界区
return TRUE;
}
OPENCSP_MutexLockerWkr::OPENCSP_MutexLockerWkr()
{
while (::InterlockedExchange(&g_lock, 1) != 0) //能以原子操作的方式交换俩个参数
{
Sleep(0);
}
}
OPENCSP_MutexLockerWkr::~OPENCSP_MutexLockerWkr()
{
::InterlockedExchange(&g_lock, 0);
}
OPENCSP_UsrMutex::OPENCSP_UsrMutex()
{
if (_dwProcessId == 0)
{
_dwProcessId = ::GetCurrentProcessId();//获取当前进程一个唯一的标识符
}
_dscs.lock();
for (;;)
{
{
OPENCSP_MutexLockerWkr locker;
if ((g_sharedProcessID == 0) ||
(g_sharedProcessID == _dwProcessId))
{
g_sharedProcessID = _dwProcessId;
break;
}
}
Sleep(1);
}
++_ulLockCnt;
}
OPENCSP_UsrMutex::~OPENCSP_UsrMutex()
{
if (--_ulLockCnt == 0)
{
OPENCSP_MutexLockerWkr locker;
g_sharedProcessID = 0;
}
_dscs.unlock();
}