Как определить, истек ли срок ожидания условия: ожидания - PullRequest
0 голосов
/ 05 февраля 2020

У меня есть класс, который позволяет ждать переменную condition_variable, заботясь о ложных пробуждениях. Ниже приведен код:

Код:

// CondVarWrapper.hpp
#pragma once
#include <mutex>
#include <chrono>
#include <condition_variable>

class CondVarWrapper {
public:
    void Signal() {
        std::unique_lock<std::mutex> unique_lock(mutex);
        cond_var_signalled = true;
        unique_lock.unlock();
        cond_var.notify_one();
    }

    // TODO: WaitFor needs to return false if timed out waiting
    bool WaitFor(const std::chrono::seconds timeout) {
        std::unique_lock<std::mutex> unique_lock(mutex);
        bool timed_out = false;
        // How to determine if wait_for timed out ?
        cond_var.wait_for(unique_lock, timeout, [this] {
            return cond_var_signalled;
        });
        cond_var_signalled = false;
        return timed_out;
    }

    void Wait() {
        std::unique_lock<std::mutex> unique_lock(mutex);
        cond_var.wait(unique_lock, [this] {
            return cond_var_signalled;
        });
        cond_var_signalled = false;
    }

private:
    bool cond_var_signalled = false;
    std::mutex  mutex;
    std::condition_variable cond_var;
};

// main.cpp
#include "CondVarWrapper.hpp"
#include <iostream>
#include <string>
#include <thread>

int main() {
   CondVarWrapper cond_var_wrapper;

   std::thread my_thread = std::thread([&cond_var_wrapper]{
       std::cout << "Thread started" << std::endl;
        if (cond_var_wrapper.WaitFor(std::chrono::seconds(1))) {
            std::cout << "Wait ended before timeout" << std::endl;
        } else {
            std::cout << "Timed out waiting" << std::endl;
        }
    });

   std::this_thread::sleep_for(std::chrono::seconds(6));
   // Uncomment following line to see the timeout working
   cond_var_wrapper.Signal();
   my_thread.join();
}

Вопрос:
В методе WaitFor мне нужно определить если cond_var истекло время ожидания? Как я могу это сделать? WaitFor должен возвращать false, когда истекло время ожидания, иначе он должен вернуть true. Это возможно?
Я вижу cv_status , объясненный на cppreference , но изо всех сил пытающийся найти хороший пример того, как его использовать.

...