C#的lock关键字用起来非常的爽。偶最近的winst库也想模拟一个.
C#中的lock关键字实际上是用Monitor类来实现的,所有首先需要一个Monitor类
class Monitor
{
typedef Pair<int, CriticalRegion> Count;
static Map<void*, Count> countMap;
public:
static void Enter(void* obj)
{
if( countMap.find(obj) != countMap.end() )
{
countMap[obj].first = countMap[obj].first + 1;
countMap[obj].second.BeginCriticalRegion();
}
else
{
countMap[obj].first = 1;
countMap[obj].second.BeginCriticalRegion();
}
}
static void Exit(void * obj)
{
if( countMap.find(obj) != countMap.end() )
{
countMap[obj].second.EndCriticalRegion();
if( countMap[obj].first == 1 )
{
countMap.erase(obj);
}
else
{
countMap[obj].first = countMap[obj].first - 1;
}
}
}
。。。。。。。。。。。。。。。。。。。。。
这是实现lock需要用到的两个函数,其中CriticalRegion类是CRITICAL_SECTION的一个简单封装
然后需要一个能够管理自动调用Enter和Exit的类
class LockHolder
{
public:
LockHolder(void * holder)
{
holder_ = holder;
Monitor::Enter(holder_);
}
~LockHolder()
{
Monitor::Exit(holder_);
}
private:
void * holder_;
};
然后就是实现lock关键字,这里偷师了boost的foreach实现
#define lock(obj) /
for(int i = 1; i > 0;)/
for(threading::LockHolder h(obj);i> 0;i--)
最后看一下如何使用
#include<iostream>
#include "winst_define.h"
#include "threading/monitor.h"
using namespace std;
using namespace winst;
using namespace winst::threading;
class A
{
public:
A()
{
cout<<"begin"<<endl;
}
void print()
{
lock(this)
{
cout<<"ok"<<endl;
Thread::Sleep(10000);
}
}
~A()
{
cout<<"end"<<endl;
}
};
int main()
{
A a;
ThreadStart start(&A::print, &a);
Thread thread1(start);
Thread thread2(start);
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
}