gpt4 book ai didi

c++ - 重置条件变量(提升)

转载 作者:行者123 更新时间:2023-11-30 05:27:01 28 4
gpt4 key购买 nike

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

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'
}
}

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

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

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 密集型的,因为这只不过是标志的轮询。不是吗?

最佳答案

是的。 condition_variable 会在每次调用 wait() 时重置。 wait() 阻塞当前线程,直到 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() 被调用)线程将处理数据,然后再次等待。

关于c++ - 重置条件变量(提升),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37536250/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com