semaphore.h

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

H
69
字号
/////////////////////////////////////////////////////////////////////////////
//
//
//                        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 __CSEMAPHORE_EX__
#define __CSEMAPHORE_EX__


class CSemaphoreEx
{
	public:
		CSemaphoreEx()
		{
			m_hSemaphore = INVALID_HANDLE_VALUE;
		}
		CSemaphoreEx(int InitialCount, int MaximumCount)
		{
			Create(InitialCount,MaximumCount);
		}
		~CSemaphoreEx()
		{
			Close();
		}
		bool Create(int InitialCount, int MaximumCount)
		{
			if(m_hSemaphore!=INVALID_HANDLE_VALUE)
				return false;
			m_hSemaphore = CreateSemaphore(NULL,InitialCount,MaximumCount,NULL);
			return true;
		}
		void Close()
		{
			if(m_hSemaphore!=INVALID_HANDLE_VALUE)
			{
				CloseHandle(m_hSemaphore);
				m_hSemaphore = INVALID_HANDLE_VALUE; 
			}
		}
		bool Acquire(DWORD timeout=INFINITE)
		{
			ASSERT(m_hSemaphore!=INVALID_HANDLE_VALUE);
			DWORD res;
			res = WaitForSingleObject(m_hSemaphore,timeout);
			return (res==WAIT_OBJECT_0);
		}
		bool Release(long ReleaseCount = 1, long *lpPreviousCount = NULL)
		{
			ASSERT(m_hSemaphore!=INVALID_HANDLE_VALUE);
			BOOL res;
			res = ReleaseSemaphore(m_hSemaphore,ReleaseCount,lpPreviousCount);
			return (res!=0);
		}
	public:
		HANDLE m_hSemaphore;
};

#endif

⌨️ 快捷键说明

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