//临界区锁 struct THREAD_CS_MUTEX { THREAD_CS_MUTEX() { InitializeCriticalSection( &m_hLock ); } ~THREAD_CS_MUTEX() { DeleteCriticalSection( &m_hLock ); } inline void Lock() { EnterCriticalSection( &m_hLock ); } inline void Unlock() { LeaveCriticalSection( &m_hLock ); } private: CRITICAL_SECTION m_hLock; }; //互斥对象锁 struct THREAD_MUTEX_GURAD { THREAD_MUTEX_GURAD():m_hMutex(INVALID_HANDLE_VALUE) { if( m_hMutex==INVALID_HANDLE_VALUE ) { m_hMutex = CreateMutex( NULL , FALSE , NULL ); } }; ~THREAD_MUTEX_GURAD() { if( m_hMutex!=INVALID_HANDLE_VALUE ) { CloseHandle( m_hMutex ); } m_hMutex = INVALID_HANDLE_VALUE ; } inline bool Lock() { bool ret = false ; if( m_hMutex!=INVALID_HANDLE_VALUE ) { DWORD wt = WaitForSingleObject( m_hMutex, INFINITE ); ret = ( WAIT_OBJECT_0 == wt ) ? true : false; } return ret; } inline bool Unlock() { bool ret = false ; if( m_hMutex!=INVALID_HANDLE_VALUE ) { ret = ReleaseMutex( m_hMutex ); } return ret; } private: HANDLE m_hMutex; }; //事件对象锁 struct THREAD_EVENT_GURAD { THREAD_EVENT_GURAD():m_hEvent(INVALID_HANDLE_VALUE) { if( m_hEvent==INVALID_HANDLE_VALUE ) { m_hEvent = CreateEvent( NULL , TRUE ,TRUE , NULL ); } }; ~THREAD_EVENT_GURAD() { if( m_hEvent!=INVALID_HANDLE_VALUE ) { CloseHandle( m_hEvent ); } m_hEvent = INVALID_HANDLE_VALUE ; } inline bool Lock() { bool ret = false ; if( m_hEvent!=INVALID_HANDLE_VALUE ) { DWORD wt = WaitForSingleObject( m_hEvent, INFINITE ); ret = ( WAIT_OBJECT_0 == wt ) ? true : false; } return ret; } inline bool Unlock() { bool ret = false ; if( m_hEvent!=INVALID_HANDLE_VALUE ) { ret = SetEvent( m_hEvent ) ; } return ret; } private: HANDLE m_hEvent; }; template<class T> class TAutoGuard { public: TAutoGuard(T &mtx) : m_mtx( mtx ) { m_mtx.Lock(); } ~TAutoGuard(void) { m_mtx.Unlock(); } protected: T &m_mtx; }; #define AUTO_GUARD( guard_tmp_var, MUTEX_TYPE , mtx ) / TAutoGuard<MUTEX_TYPE> guard_tmp_var(mtx)