今天看到有人在討論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;
}
輸出結果:

完整代碼:
//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