MyBlog++

#arduino #beginner #game #qt #qt3d #rendering

A simple Event class for thread synchronization

22 May 2017 - #beginner

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:
    inline void reset()
    {
        _isRaised = false;
    }

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

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

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

    inline 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.


author-logo zeduckmaster
just another senior C++ developper
mastodon-logo framagit-logo rss-symbol

Creative Commons Licence
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.