Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 条件变量和无锁容器_C++_Multithreading_Condition Variable - Fatal编程技术网

C++ 条件变量和无锁容器

C++ 条件变量和无锁容器,c++,multithreading,condition-variable,C++,Multithreading,Condition Variable,条件变量使用互斥锁,.wait()函数将解锁 互斥,以便其他线程可以访问共享数据。当情况 变量被通知它再次尝试锁定互斥锁以使用共享 数据 此模式用于以下来自的并发队列示例: 生产商/主线程: const bool was_empty = the_queue.empty(); Data d; the_queue.push(d); if(was_empty) cond_var.notify_one(); 关闭程序: bool expected_run_state = true; if(runLo

条件变量使用互斥锁,.wait()函数将解锁 互斥,以便其他线程可以访问共享数据。当情况 变量被通知它再次尝试锁定互斥锁以使用共享 数据

此模式用于以下来自的并发队列示例:

生产商/主线程:

const bool was_empty = the_queue.empty();
Data d; 
the_queue.push(d);
if(was_empty) cond_var.notify_one();
关闭程序:

bool expected_run_state = true;
if(runLoop.compare_exchange_strong(expected_run_state, false))
{
    //atomically set our loop flag to false and 
    //notify all clients of the queue to wake up and exit
    cond_var.notify_all();
}
如上所述,这段代码似乎有效,但这并不一定意味着它是正确的。尤其是仅因为条件变量接口迫使我使用互斥而使用的本地互斥,这似乎是一个非常糟糕的主意。我想使用条件变量,因为添加到队列中的数据项之间的时间很难预测,我必须创建睡眠和定期醒来,如下所示:

if(the_queue.empty()) Sleep(short_amount_of_time);

是否有其他特定于操作系统(在我的例子中是Windows)的工具,可以使后台线程在满足某个条件之前一直处于休眠状态,而无需定期唤醒和检查该条件?

例如,在不同的场景中,代码是不正确的。当
const bool为_empty时,如果队列只有一个元素,则=_queue.empty(),但一个线程使用该元素,而另一个线程尝试使用并等待该条件,写入程序在将该元素插入队列后不会通知该线程

关键问题是,接口中的所有操作都是线程安全的,这并不一定意味着您对接口的使用是安全的。如果您依赖于以原子方式执行多个操作,则需要在外部提供同步机制

是否还有其他特定于操作系统(在我的例子中是Windows)的工具, 使后台线程睡眠直到满足某些条件 没有定期醒来检查病情

这正是我们的目的

但是,如果您只针对Windows平台(Vista+),您应该查看

虽然我已经选择了你的答案,但还有一个问题。如果没有共享状态,也就是说,我不会检查\u queue.empty()
,而是总是调用
cond.notify()
,这是否表明我可以安全地使用实际上不锁定任何内容的本地互斥锁?当然,这意味着我会尝试太频繁地唤醒后台任务,但当没有人在等待条件变量时,通知可能不会造成任何伤害,不是吗?一段时间过去了,现在我可以对您的答案进行投票。所以我现在就这么做了。再次感谢。
bool expected_run_state = true;
if(runLoop.compare_exchange_strong(expected_run_state, false))
{
    //atomically set our loop flag to false and 
    //notify all clients of the queue to wake up and exit
    cond_var.notify_all();
}
if(the_queue.empty()) Sleep(short_amount_of_time);