mutex.h

来自「这是书上的代码」· C头文件 代码 · 共 71 行

H
71
字号
/////////////////////////////////////////////////////////////////////////////
//
//
//                        Copyright Declaration
//        
//            This source code is designed by Huang Yifeng(China).
//       You can use the source code, but please reserve the Copyright
//       Declaration in this code. Or you should be ready to be punished
//       by the related law.
//
//                                                  Huang Yifeng
//                                              edward_hyf@sohu.com
//                                                    2003.7.8
//////////////////////////////////////////////////////////////////////////////

#ifndef __Mutex__
#define __Mutex__


class CMutexEx
{
	public:
		CMutexEx()
		{
			m_hMutex = INVALID_HANDLE_VALUE;
			Create();
		}
		~CMutexEx()
		{
			Close();
		}
		bool Create()
		{
			if(m_hMutex!=INVALID_HANDLE_VALUE)
				return false;
			m_hMutex = CreateMutex(NULL,false,NULL);
			return true;
		}
		void Close()
		{
			if(m_hMutex!=INVALID_HANDLE_VALUE)
			{
				CloseHandle(m_hMutex);
				m_hMutex = INVALID_HANDLE_VALUE; 
			}
		}
		void Lock()
		{
			ASSERT(m_hMutex!=INVALID_HANDLE_VALUE);
			DWORD res = WaitForSingleObject(m_hMutex,INFINITE);
			ASSERT(res==WAIT_OBJECT_0);
		}
		void Unlock()
		{
			ASSERT(m_hMutex!=INVALID_HANDLE_VALUE);
			BOOL ret = ReleaseMutex(m_hMutex);
			ASSERT(ret==TRUE);
		}
		bool IsValid()
		{
			return (m_hMutex==INVALID_HANDLE_VALUE)?false:true;
		}
		operator HANDLE()
		{
			return m_hMutex;
		}
	public:
		HANDLE m_hMutex;
};

#endif

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?