c++ - Synchronization with blocking call -


suppose have class following interface:

class ievent {     void setevent() = 0;     void waitforevent() = 0; } 

waitforevent() blocking function waits until thread calls setevent() function.

i'm writing unit tests class , want following scenario:

first thread calls waitforevent(). after second thread calls setevent().

how synchronize threads setevent() call follow waitforevent() call?

i don't want use sleeps because want unit tests run fast possible.

this best manage

#include <mutex> #include <condition_variable> #include <thread> #include <iostream>  class ievent { public:     virtual void setevent() = 0;     virtual void waitforevent() = 0; };  class eventclass : public ievent { public:     void setevent() override {         std::unique_lock<std::mutex> lock { _mutex };         std::cout << "setting event\n";         _event = true;         lock.unlock();         _cv.notify_all();     }      void waitforevent() override {         std::unique_lock<std::mutex> lock { _mutex };         std::cout << "waiting event\n";         _cv.wait(lock, [this]{ return _event; });         std::cout << "waiting complete\n";     };  private:     std::mutex _mutex;     std::condition_variable _cv;     bool _event = false; };  int main() {     eventclass object;      std::mutex cv_mutex;     std::condition_variable may_set_cv;     bool may_set_event = false;      auto setting_thread = std::thread([&]{         std::unique_lock<std::mutex> lock { cv_mutex };         may_set_cv.wait(lock,                         [&] {                             return may_set_event;                         });         object.setevent();     });     std::unique_lock<std::mutex> lock { cv_mutex };     may_set_event = true;     lock.unlock();     may_set_cv.notify_one();      // tiny race condition here      object.waitforevent();      setting_thread.join(); } 

Comments