码迷,mamicode.com
首页 > 其他好文 > 详细

OpenCSP开源程序解析之OPENCSP_Mutex.cpp

时间:2015-06-06 09:14:27      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:opencsp

#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();
}

OpenCSP开源程序解析之OPENCSP_Mutex.cpp

标签:opencsp

原文地址:http://blog.csdn.net/sjtu_chenchen/article/details/46383189

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!