No++

No++

Just another blog on C++, GFX and other stuff

22 May 2017

A simple event class

When you start learning and dealing with thread and synchronization, code can become hard to manage very fast. So I propose you a very small Event class to help you in this case.

The goal of this class is not performance, but to be simple enough for beginners to understand the very basic of thread synchronization.

The code is based on modern C++, but can be adapted on older C++ implementation with the help of the boost library.

Code

#include <mutex>
#include <condition_variable>
#include <chrono>

class Event final
{
public:
  void reset()
  {
    _isRaised = false;
  }

  void wait()
  {
    std::unique_lock<std::mutex> lock{_mutex};
    while(_isRaised == false)
      _cond.wait(lock);
  }

  void waitFor(size_t ms)
  {
    std::unique_lock<std::mutex> lock{_mutex};
    while(_isRaised == false)
      _cond.wait_for(lock, std::chrono::milliseconds{ms});
  }

  void raise()
  {
    std::lock_guard<std::mutex> lock{_mutex};
    _isRaised = true;
    _cond.notify_all();
  }

  bool isRaised() const
  {
    return _isRaised;
  }

private:
  std::condition_variable _cond;
  std::mutex _mutex;
  bool _isRaised = false;
};

How to use it

Just create an instance of this class on a main thread, and pass the address of it (via reference or pointer) to the other thread(s) for synchonization.

Then use wait() function on the thread(s) you want to wait until the worker thread has finished its work. Call raise() on the worker thread to signal waiting thread(s) to stop waiting.

Don’t forget to use reset() function if you want to synchronize your threads again with the same Event instance.