C++跨平台事件机制实现

今天看到有人在讨论C++标准没有提供类似操作系统层次的事件通知机制,如windows的事件内核对象。其实我想说的事,C++11标准里的互斥量及条件变量已经够帮我们实现类似的功能了。

刚编写了一个事件通知类新鲜出炉,供大家把玩一下,一起学习并发线程的编写。写的有不好的地方,请一定要不吝惜指出来,我会改正,谢谢!

废话不说,上代码,为了够能编译成功,请用支持C++11的编辑器,我用的是Vs2012。为了凑够150字,用例代码就直接贴这里:

#include "event.hpp"

event my_event;

void threadproc3()
{
my_event.wait();
cout << "threadproc3\n";
}

void threadproc4()
{
my_event.wait();
cout << "threadproc4\n";
}

int main()
{
my_event.notify_all();

thread t1(threadproc3);
thread t2(threadproc4);

//while(true)
{
system("pause");
my_event.notify_all();
}

t1.join();
t2.join();

return 0;
}

输出结果:

C++跨平台事件机制实现

完整代码:

//event.hpp

#ifndef EVENT_INCLUDE
#define EVENT_INCLUDE #include <mutex>
#include <condition_variable>
#include <atomic> // 利用C++11的锁与条件变量实现跨平台的事件通知机制
class event
{
public:
event()
{
_state = false;
} void wait()
{
// 这里的状态设置不使用强同步,允许同一时刻多个线程唤醒也没什么问题
if (_state==true)
{
_state = false;
return;
}
std::unique_lock<std::mutex> _lock(_mutex);
_var.wait(_lock);
_state = false;
} template<typename T>
bool wait_for(T&& t)
{
// 这里的状态设置不使用强同步,允许同一时刻多个线程唤醒也没什么问题
if (_state==true)
{
_state = false;
return true;
}
std::unique_lock<std::mutex> _lock(_mutex);
std::cv_status::cv_status re = _var.wait_for(_lock,std::forward<T>(t));
if (re!=std::cv_status::cv_status::timeout)
{
_state = false;
return true;
}
return false;
} template<typename T>
bool wait_util(T&& t)
{
// 这里的状态设置不使用强同步,允许同一时刻多个线程唤醒也没什么问题
if (_state==true)
{
_state = false;
return true;
}
std::unique_lock<std::mutex> _lock(_mutex);
std::cv_status::cv_status re = _var.wait_until(_lock,std::forward<T>(t));
if (re!=std::cv_status::cv_status::timeout)
{
_state = false;
return true;
}
return false;
} void notify_all()
{
_var.notify_all();
_state = true;
} void notify_once()
{
_var.notify_one();
_state = true;
} private:
event(const event&);
event& operator=(const event&);
event(event&&); protected:
std::mutex _mutex;
std::condition_variable _var;
std::atomic<bool> _state; // 件事的状态
}; #endif
上一篇:java 修改文件


下一篇:hiho1257 Snake Carpet