0

我正在处理一个 c++ (11) 项目,在主线程上,我需要检查两个变量的值。这两个变量的值将由其他线程通过两个不同的回调来设置。我正在使用两个条件变量来通知这两个变量的变化。因为在 C++ 中,条件变量需要锁,我不确定是否应该为两个条件变量使用相同的互斥锁,或者我应该使用两个互斥锁来最小化独占执行。不知何故,我觉得一个互斥体就足够了,因为在一个线程(在这种情况下为主线程)上,代码无论如何都会按顺序执行。检查(等待)两个变量值的主线程上的代码无论如何都不会交错。如果您需要我编写代​​码来说明问题,请告诉我。我可以准备那个。谢谢。

更新,添加代码:

#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();
}
4

0 回答 0