Clean queue after X seconds with possibility to extend timer

  c++, locking, multithreading, queue, thread-safety

Its supposed to clean-up the std::queue 3 seconds after last call of AddPoints function, in a thread-safe way. Each call should delay the clean-up to 3 seconds. There should be only one Process thread running at time.

class PointsHandler
{
public:
    struct Points
    {
        void* source;
        int   points;
    };

    void Process()
    {
        std::unique_lock<std::mutex> lock(mtx);
    
        // other threads should be able to add
        // more points while this one is waiting
        wakeup.wait_until(lock, timeout, [this] // timeout is passed as ref here, I found that
        {                                       // modyfing it from outside actually works
            return ( false ); // placeholder for some condition
        });

        int points = 0;
        while (!queue.empty()) {
            auto e = queue.front();
            queue.pop();
            
            points += e.points;           
        }   
        ExternalFunc(points);
    }

    void AddPoints(const Points& points)
    {
        std::unique_lock<std::mutex> lock(mtx);

        queue.push(points);

        timeout = clock_t::now() + std::chrono::seconds(3); // extend timer

        if (!worker.valid() || worker.wait_for(0ms) == std::future_status::ready) {
            worker = std::async(std::launch::async, &MyClass::Process, this);
        }
    }
    
private:
    using clock_t = std::chrono::steady_clock;
    using timepoint_t = clock_t::time_point;

    std::queue<Points>       queue;
    mutable std::mutex       mtx;
    std::condition_variable  wakeup;
    std::future<void>        worker;
    timepoint_t              timeout;
};

Source: Windows Questions C++

LEAVE A COMMENT