C ++ cross-platform event mechanism implementation and event mechanism
Today, we can see that the C ++ standard does not provide event notification mechanisms similar to the operating system level, such as windows event kernel objects. In fact, the mutex and conditional variables in the C ++ 11 standard are enough to help us implement similar functions.
I have just compiled an Event Notification class for everyone to take a look and learn how to write concurrent threads. If something is wrong, please do not hesitate to point it out. I will correct it. Thank you!
In order to compile the code successfully, please use an editor that supports C ++ 11. I use Vs2012. In order to make up 150 words, the use case code is directly pasted here:
# 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.policy_all ();
Thread t1 (threadproc3 );
Thread t2 (threadproc4 );
// While (true)
{
System ("pause ");
My_event.policy_all ();
}
T1.join ();
T2.join ();
Return 0;
}
Output result:
Complete code:
// Event. hpp # ifndef EVENT_INCLUDE # define EVENT_INCLUDE # include <mutex> # include <condition_variable> # include <atomic> // implement cross-platform event notification using the locks and conditional variables of C ++ 11 class event {public: event () {_ state = false;} void wait () {// The status settings here do not use forced synchronization, it's okay to allow multiple threads to wake up at the same time. if (_ state = true) {_ state = false; return;} std: unique_lock <std :: mutex> _ lock (_ mutex); _ var. wait (_ lock); _ state = false;} template <typename T> bool wait_fo R (T & t) {// The status settings here do not use strong synchronization. It is okay to allow multiple threads to wake up at the same time if (_ state = true) {_ state = false; return true;} std: unique_lock <std: mutex> _ lock (_ mutex); std: cv_status re = _ var. wait_for (_ lock, std: forward <T> (t); if (re! = Std: cv_status: timeout) {_ state = false; return true;} return false;} template <typename T> bool wait_util (T & t) {// The status settings here do not use strong synchronization. It is no problem to allow multiple threads to wake up at the same time. if (_ state = true) {_ state = false; return true;} std: unique_lock <std: mutex> _ lock (_ mutex); std: cv_status re = _ var. wait_until (_ lock, std: forward <T> (t); if (re! = Std: cv_status: timeout) {_ state = false; return true;} return false;} void policy_all () {_ var. policy_all (); _ state = true;} void policy_once () {_ var. policy_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; // event status}; # endif