0

I am working on a c++ (11) project and on the main thread, I need to check the value of two variables. The value of the two variables will be set by other threads through two different callbacks. I am using two condition variables to notify changes of those two variables. Because in c++, locks are needed for condition variables, I am not sure if I should use the same mutex for the two condition variables or I should use two mutex's to minimize exclusive execution. Somehow, I feel one mutex should be sufficient because on one thread(the main thread in this case) the code will be executed sequentially anyway. The code on the main thread that checks (wait for) the value of the two variables wont be interleaved anyway. Let me know if you need me to write code to illustrate the problem. I can prepare that. Thanks.

Update, add code:

#include <mutex>

class SomeEventObserver {
public:
    virtual void handleEventA() = 0;
    virtual void handleEventB() = 0;
};

class Client : public SomeEventObserver {
public:
    Client() {
        m_shouldQuit = false;
        m_hasEventAHappened = false;
        m_hasEventBHappened = false;
    }

    // will be callbed by some other thread (for exampe, thread 10)
    virtual void handleEventA() override {
        {
            std::lock_guard<std::mutex> lock(m_mutexForA);
            m_hasEventAHappened = true; 
        }

        m_condVarEventForA.notify_all();
    }


    // will be called by some other thread (for exampe, thread 11)
    virtual void handleEventB() override {
        {
            std::lock_guard<std::mutex> lock(m_mutexForB);
            m_hasEventBHappened = true; 
        }
        m_condVarEventForB.notify_all();
    }


    // here waitForA and waitForB are in the main thread, they are executed sequentially 
    // so I am wondering if I can use just one mutex to simplify the code
    void run() {
        waitForA();
        waitForB();
    }

    void doShutDown() {
        m_shouldQuit =  true;
    }

private:
    void waitForA() {
        std::unique_lock<std::mutex> lock(m_mutexForA);
        m_condVarEventForA.wait(lock, [this]{ return m_hasEventAHappened; });
    }

    void waitForB() {
        std::unique_lock<std::mutex> lock(m_mutexForB);
        m_condVarEventForB.wait(lock, [this]{ return m_hasEventBHappened; });
    }

    // I am wondering if I can use just one mutex
    std::condition_variable m_condVarEventForA;
    std::condition_variable m_condVarEventForB;
    std::mutex m_mutexForA;
    std::mutex m_mutexForB;
    bool m_hasEventAHappened;
    bool m_hasEventBHappened;

    };

int main(int argc, char* argv[]) {
    Client client;
    client.run();
}
Queen W
  • 1
  • 1

0 Answers0