#ifndef _AUTOLOCK_H #define _AUTOLOCK_H #ifndef _WIN32 #include #include #include #endif //NOT _WIN32 class CLockObject { private: CRITICAL_SECTION m_Section; bool m_bInit; public: inline CLockObject():m_bInit(false){Init();} inline ~CLockObject(){if(m_bInit)::DeleteCriticalSection(&m_Section);} inline void Init(){if(!m_bInit)::InitializeCriticalSection(&m_Section);m_bInit=true;} inline void Clear(){if(m_bInit)::DeleteCriticalSection(&m_Section);m_bInit=false;} inline void Lock(){::EnterCriticalSection(&m_Section);} inline void Unlock(){::LeaveCriticalSection(&m_Section);} inline bool Trylock(){return ::TryEnterCriticalSection(&m_Section)==TRUE;} }; class CAutoLock { private: CLockObject *m_pObject; public: inline CAutoLock(CLockObject *pObject,DWORD nTimeOut=0):m_pObject(pObject) { if(m_pObject==NULL) return; if(nTimeOut==0) m_pObject->Lock(); else { DWORD nBegin(::GetTickCount()); while(!m_pObject->Trylock()) { if(!SwitchToThread()) Sleep(100); if(GetTimeDistance(nBegin)>=nTimeOut) { m_pObject=NULL; //assert(false); break; } } } } inline ~CAutoLock() { if(m_pObject) m_pObject->Unlock(); } inline DWORD GetTimeDistance(DWORD nBegin) { DWORD nEnd(::GetTickCount()); if(nEnd>=nBegin) return nEnd-nBegin; else return nEnd+!nBegin+1; } }; #endif//_AUTOLOCK_H