ManualResetEvent.h
/* ---------------------------------------------------------- * 文件名称:ManualResetEvent.h * * 作者:秦建辉 * * MSN:splashcn@msn.com * QQ:36748897 * * 博客:http://www.firstsolver.com/wordpress/ * * 开发环境: * Qt Creator 2.6.0 * Qt Library 4.8.3 * Ubuntu 12.10 * * 版本历史: * V1.0 2012年11月27日 * 实现C#中的ManualResetEvent类 ------------------------------------------------------------ */ #ifndef MANUALRESETEVENT_H #define MANUALRESETEVENT_H #include <QMutex> #include <QWaitCondition> class ManualResetEvent { public: /* * 构造函数,设置初始状态 */ ManualResetEvent(bool initialState); /* * 功能:阻止当前线程,直到收到信号或者超过指定的时间 */ bool WaitOne(unsigned long time = ULONG_MAX); /* * 功能:将事件状态设置为终止状态,允许一个或多个等待线程继续 */ void Set(); /* * 功能:将事件状态设置为非终止状态,导致线程阻止 */ void Reset(); private: /* * 状态标记,true表示终止状态,false表示非终止状态 */ volatile bool open; // 注意:阻止编译器对其进行优化 QMutex mutex; // 互斥量 QWaitCondition monitor; // 条件等待信号量 }; #endif // MANUALRESETEVENT_H
ManualResetEvent.cpp
#include "ManualResetEvent.h" #include <QMutexLocker> // 构造函数 ManualResetEvent::ManualResetEvent(bool initialState) { // 初始化终止状态标记 open = initialState; } // 阻止当前线程,直到收到信号或者超过指定的时间 bool ManualResetEvent::WaitOne(unsigned long time) { QMutexLocker locker(&mutex); if(!open)monitor.wait(&mutex, time); // 等待信号 return open; } // 将事件状态设置为终止状态,允许一个或多个等待线程继续 void ManualResetEvent::Set() { QMutexLocker locker(&mutex); open = true; monitor.wakeAll(); } // 将事件状态设置为非终止状态,导致线程阻止 void ManualResetEvent::Reset() { open = false; }