绑定条件谓词块子线程

Bound Conditional predicate blocks child thread

我正在尝试创建一个线程,该线程通过条件变量获得通知以执行某些代码。我将线程绑定到一个 class 成员函数,如下所示:

m_dbSaver = std::thread(std::bind(&ContactLearningApp::DBWorkerThread, this));
m_lk = std::unique_lock<std::mutex>(m_mutex);
m_Processed = true;

每隔半秒,我尝试 运行 这样的线程:

if (m_sampleClock.getTimeMilliseconds() > 500) {
        printf("Save samples to DB\n");
        // Wait for worker to finish processing
        m_cv.wait(m_lk, [this] {return this->m_Processed; });
        // Instruct thread to execute
        m_Ready = true;
        m_cv.notify_one();
        m_sampleClock.reset();
}

我的工作线程看起来像这样:

void ContactLearningApp::DBWorkerThread() {

    std::unique_lock<std::mutex> ul(m_mutex);
    printf("Start worker thread. \n");
    while (true) {
        printf("Inside while loop and waiting. \n");
        m_cv.wait(ul, [this] {return this->m_Ready; });
        printf("Condition passed. \n");
        m_Processed = false;
        std::cout << "Worker thread processing data. " << std::endl;
        m_Processed = true;
        ul.unlock();
        m_cv.notify_one();
    }

}

即使我将 m_Ready 谓词设置为真,工作线程也从未通过条件。如果我在创建线程之前将 m_Ready 变量设置为 true,则条件通过。我这样做正确吗?

第一次通过工作循环你有锁,第二次你没有锁。

Wait until notified

The execution of the current thread (which shall have locked lck's mutex) is blocked until notified.

需要加锁

printf("Start worker thread. \n");
while (true) {
    printf("Inside while loop and waiting. \n");
    std::unique_lock<std::mutex> ul(m_mutex);
    m_cv.wait(ul, [this] {return this->m_Ready; });
    printf("Condition passed. \n");
    m_Processed = false;
    std::cout << "Worker thread processing data. " << std::endl;
    m_Processed = true;
    ul.unlock();
    m_cv.notify_one();
}

这应该会增加您做对的机会。