c++ 自定义 lock

#include <windows.h>
#pragma comment(lib, "Kernel32.lib")


#define mylock(M) for(ZhkLock tmplock=M; tmplock; tmplock.SetUnlock())

class ZhkMutex
{
public:
	ZhkMutex(void);
public:
	virtual ~ZhkMutex(void);

public:
    void  ZhkLock();
	void  UnLock();
private:
   CRITICAL_SECTION m_criticalSection;
};

class ZhkLock
{
public:
	ZhkLock(ZhkMutex &mutex);
~ZhkLock(void);
void SetUnlock();
operator bool () const;
private:
	ZhkMutex &m_mutex;
	bool m_locked;
};

#include "ZhkMutex.h"

ZhkLock::ZhkLock(ZhkMutex&mutex)
: m_mutex(mutex), m_locked(true)
{
	    m_mutex.ZhkLock();
}

ZhkLock::~ZhkLock(void)
{/*一定要在析构函数中解锁,因为不管发生什么,只要对象离开他的生命周期(即离开大括号),都会调用其析构函数*/
	     m_mutex.UnLock();
}

void ZhkLock::SetUnlock()
{
	     m_locked = false;
}

ZhkLock::operator bool() const
{
	    return m_locked;


}


ZhkMutex.cpp
#include "StdAfx.h"
#include "ZhkMutex.h"

#include <Windows.h>

ZhkMutex::ZhkMutex(void)
{
	InitializeCriticalSection(&m_criticalSection);
}

ZhkMutex::~ZhkMutex(void)
{
	DeleteCriticalSection(&m_criticalSection);//保证对象被析构时候能够删除临界区
}

void ZhkMutex::ZhkLock()
{
	EnterCriticalSection(&m_criticalSection);
}

void ZhkMutex::UnLock()
{
LeaveCriticalSection(&m_criticalSection);
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值