重置条件变量(提升)

Resetting the conditional variable (boost)

如果有人问过这个问题,我深表歉意。
是否可以清除已经设置的条件变量?
下面是我想要实现的详细信息:

void worker_thread {
    while (wait_for_conditional_variable_execute) {
        // process data here
        // Inform main thread that the data got processed
        // Clear the conditional variable 'execute'
    }
}

注意工作线程应该只处理一次数据,它应该等待主线程再次设置"execute"条件变量

我也想过像下面这样的旗帜

void worker_thread {
    while (wait_for_conditional_variable_execute) {
        if (flag) { flag = 0; }
        // process data here. The `flag` will be set by main thread
        }
}

但我认为这将是 CPU 密集的,因为这只是对标志的轮询。不是吗?

是的。每当调用 wait() 时,都会重置 condition_variablewait() 阻塞当前线程,直到 condition_variable 唤醒 可以这么说。

不过,您似乎没有正确使用 condition_variable。而不是说

while (wait_for_conditional_variable_execute)

你真的很想说

while (thread_should_run)
{
    // wait_for_conditional_variable_execute
    cv.wait();
}

这会给你带来以下效果:

void processDataThread()
{
    while (processData)
    {
        // Wait to be given data to process
        cv.wait();
        // Finished waiting, so retrieve data to process
        int n = getData();
        // Process data:
        total += n;
    }
}

那么在你的主线程中你将拥有:

addData(16);
cv.notify_all();

您的线程将处理数据,重新进入while循环然后等待condition_variable被触发。一旦触发(即调用 notify())线程将处理数据,然后再次等待。