C++模拟C# lock关键字

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的一个简单封装

然后需要一个能够管理自动调用EnterExit的类

        class LockHolder

        {

          public:

                LockHolder(void * holder)

                {

                    holder_ = holder;

                    Monitor::Enter(holder_);

                }

 

                ~LockHolder()

                {

                    Monitor::Exit(holder_);

                }

 

          private:

                void * holder_;

        };

 

然后就是实现lock关键字,这里偷师了boostforeach实现

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

}

 

 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值