绑定条件谓词阻止子线程

时间:2016-12-12 21:30:57

标签: c++ multithreading condition-variable

我正在尝试创建一个通过Conditional变量通知执行某些代码的线程。我将线程绑定到类成员函数,如下所示:

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

My Worker线程看起来像这样:

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谓词设置为true,工作线程也不会传递条件。如果在创建线程之前将m_Ready变量设置为true,则条件通过。我这样做了吗?

1 个答案:

答案 0 :(得分:0)

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

  

等到收到通知

     

当前线程的执行(应该   锁定lck的互斥锁被阻止,直到得到通知。

需要锁定。

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

这可以提高你做对的机会。