用C++实现Win32事件对象,同步线程
用C++实现Win32事件对象,同步线程
在Win32环境下编写多线程应用程序,经常要用到事件对象Event,来进行线程同步。与其相关的一组API包括:CreateEvent,SetEvent,ResetEvent,WaitForSingleObject,和CloseHandle。关于这些API的功能以及参数意义等这里就不多说了。下边,我封装了一个事件对象类,以及测试代码。已由本人在VS2005环境下编译,测试通过。MyEvent.h
- #ifndef My_Event_Header
- #define My_Event_Header
- #include <iostream>
- #ifdef WIN32
- #include <Windows.h>
- #endif
- using namespace std;
- //---------------------------------------------------------------
- class CEventImpl
- {
- protected:
- /*
- 创建一个匿名事件对象
- `bAutoReset true 人工重置
- false 自动重置
- */
- CEventImpl(bool bManualReset);
- /*
- 销毁一个事件对象
- */
- ~CEventImpl();
- /*
- 将当前事件对象设置为有信号状态
- 若自动重置,则等待该事件对象的所有线程只有一个可被调度
- 若人工重置,则等待该事件对象的所有线程变为可被调度
- */
- void SetImpl();
- /*
- 以当前事件对象,阻塞线程,将其永远挂起
- 直到事件对象被设置为有信号状态
- */
- bool WaitImpl();
- /*
- 以当前事件对象,阻塞线程,将其挂起指定时间间隔
- 之后线程自动恢复可调度
- */
- bool WaitImpl(long lMilliseconds);
- /*
- 将当前事件对象设置为无信号状态
- */
- void ResetImpl();
- private:
- HANDLE h_Event;
- };
- inline void CEventImpl::SetImpl()
- {
- if (!SetEvent(h_Event))
- {
- cout<<"cannot signal event"<<endl;
- }
- }
- inline void CEventImpl::ResetImpl()
- {
- if (!ResetEvent(h_Event))
- {
- cout<<"cannot reset event"<<endl;
- }
- }
- //---------------------------------------------------------------
- class CMyEvent: private CEventImpl
- {
- public:
- CMyEvent(bool bManualReset = true);
- ~CMyEvent();
- void Set();
- bool Wait();
- bool Wait(long milliseconds);
- bool TryWait(long milliseconds);
- void Reset();
- private:
- CMyEvent(const CMyEvent&);
- CMyEvent& operator = (const CMyEvent&);
- };
- inline void CMyEvent::Set()
- {
- SetImpl();
- }
- inline bool CMyEvent::Wait()
- {
- return WaitImpl();
- }
- inline bool CMyEvent::Wait(long milliseconds)
- {
- if (!WaitImpl(milliseconds))
- {
- cout<<"time out"<<endl;
- return false;
- }
- else
- {
- return true;
- }
- }
- inline bool CMyEvent::TryWait(long milliseconds)
- {
- return WaitImpl(milliseconds);
- }
- inline void CMyEvent::Reset()
- {
- ResetImpl();
- }
- #endif
|
评论暂时关闭