std :: condition_variable虚假阻塞 [英] std::condition_variable spurious blocking

查看:131
本文介绍了std :: condition_variable虚假阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所知,应该循环调用条件变量,以避免虚假唤醒。像这样:

As you know, condition variables should be called in cycle to avoid spurious wake-ups. Like this:

while (not condition)
    condvar.wait();

如果另一个线程想要唤醒等待的线程,则必须将条件标记设置为true。例如:

If another thread wants to wake up waiting thread, it must set condition flag to true. E.g.:

condition = true;
condvar.notify_one();

我想知道,这种情况是否有可能阻塞条件变量:

I wonder, is it possible for condition variable to be blocked by this scenario:

1)等待线程检查条件标志,并发现它等于FALSE,因此,它将输入 condvar.wait()

1)Waiting thread checks condition flag, and finds it is equal to FALSE, so, it's going to enter condvar.wait() routine.

2)但是在此之前(但在条件标志检查之后)内核已抢占了等待线程(例如,由于时隙到期)。

2)But just before this (but after condition flag checking) waiting thread is preempted by kernel (e.g. because of time slot expiration).

3)这时,另一个线程要通知等待线程有关情况。它将条件标志设置为TRUE并调用 condvar.notify_one();

3) At this time, another thread wants to notify waiting thread about condition. It sets condition flag to TRUE and calls condvar.notify_one();

4)当内核调度程序运行第一个线程时再次,它进入 condvar.wait()例程,但是已经错过了通知。

4) When kernel scheduler runs first thread again, it enters condvar.wait() routine, but the notification have been already missed.

所以,等待尽管条件标志设置为TRUE,线程仍无法从 condvar.wait()退出,因为不再有唤醒通知。

So, waiting thread can't exit from condvar.wait(), despite condition flag is set to TRUE, because there is no wake up notifications anymore.

有可能吗?

推荐答案

这正是为什么条件变量必须与a结合使用的原因互斥体,以自动更新状态并发出更改信号。完整代码看起来像这样:

That is exactly why a condition variable must be used in conjunction with a mutex, in order to atomically update the state and signal the change. The full code would look more like:

unique_lock<mutex> lock(mutex);
while (not condition)
    condvar.wait(lock);

,对于另一个线程:

lock_guard<mutex> lock(mutex);
condition = true;
condvar.notify_one();

这篇关于std :: condition_variable虚假阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆