#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); }
c++ 自定义 lock
最新推荐文章于 2023-09-17 14:41:34 发布