dimanche 21 novembre 2021

Usage of condition variable and create a simple reusable class

I have created a class using condition variable where I can create an object and use it instead of writing the implementation of the condition variable.

Below is my code. Now the functionality works as expected.

I see some issues if I run valgrind. So I have two requests.

  1. Please check the class implementation of the class and confirm if there can be any issues.
  2. There is a "still reachable" error in valgrind if I run a gtest with this code. I checked online and found that "still reachable" issue can be ignored and moreover this problem is shown even if I do not add any code inside the test case (empty test case). So I am not too much worried about this error.

here is my code.

//ConditionalVariable.h


#ifndef SOURCE_MBUTILS_CONDITIONALVARIABLE_H_
#define SOURCE_MBUTILS_CONDITIONALVARIABLE_H_

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

class ConditionalVariable {
public:
    ConditionalVariable();
    virtual ~ConditionalVariable();

    /**
     * wait for the condition to reset from thread 1
     */
    void waitForCondition();

    /**
     * wait for the condition to reset from thread 1 for timeout (msec)
     * returns false if timeout, true otherwise
     */
    bool waitForCondtion(std::uint32_t timeout);

    /**
     * reset the condition from thread 1, normally after the wait is over!
     */
    void resetCondition();

    /**
     * set the condition from thread 2
     */
    void setTheCondition();

    /**
     * get current condition state
     */
    bool isConditionNowSet();
private:
    std::mutex _mtx;
    std::condition_variable _cv;
    bool _condition;
};

#endif /* SOURCE_MBUTILS_CONDITIONALVARIABLE_H_ */

//ConditionalVariable.cpp

#include "ConditionalVariable.h"

ConditionalVariable::ConditionalVariable(): _condition(false)
{
    // TODO Auto-generated constructor stub

}

ConditionalVariable::~ConditionalVariable() {
    // TODO Auto-generated destructor stub
}

void ConditionalVariable::waitForCondition()
{
    std::unique_lock<std::mutex> lock(_mtx);
    _cv.wait(lock, [this]{ return _condition;});
}

bool ConditionalVariable::waitForCondtion(std::uint32_t timeout)
{
    auto timePoint = std::chrono::system_clock::now() + (std::chrono::milliseconds) timeout;
    std::unique_lock<std::mutex> lock(_mtx);
    return _cv.wait_until(lock, timePoint, [this]{return _condition;});
}
void ConditionalVariable::resetCondition() {
    //make the condition false to reset!
    std::lock_guard<std::mutex> lock(_mtx);
    _condition = false;
}

void ConditionalVariable::setTheCondition()
{
    std::lock_guard<std::mutex> lock(_mtx);
    _condition = true;
    _cv.notify_one();
}
bool ConditionalVariable::isConditionNowSet()
{
    return _condition;
}

Below error is from valgrind

enter image description here

Aucun commentaire:

Enregistrer un commentaire