C ++ 11我可以确保condition_variable.wait()不会错过通知? [英] C++11 Can I ensure a condition_variable.wait() won't miss a notification?

查看:96
本文介绍了C ++ 11我可以确保condition_variable.wait()不会错过通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有线程1执行以下代码:

I have thread 1 executing the following code:

unique_lock<mutex> ul(m);
while(condition == true)
    cv.wait(ul);

并且执行此代码的线程2:

And thread 2 executing this code:

condition = false;
cv.notify_one();

不幸的是,我遇到了时间问题:

Unfortunately I'm hitting a timing issue:

T1: condition checks true
                            T2: condition set to false
                            T2: cv.notify_one()
T1: cv.wait()

线程1完全错过了通知,并且在wait()上保持阻塞。我试着使用版本的wait(),它接受一个谓词,但基本上相同的结果。也就是说,谓词的主体执行检查,但在返回之前,条件的值将更改并发送通知。

Thread 1 misses the notification completely and remains blocked on wait(). I tried using the version of wait() which takes a predicate but with essentially the same result. That is, the body of the predicate performs the check, but before it returns, the condition's value is changed and the notification is sent. The predicate then returns.

如何解决这个问题?

推荐答案

>你应该通过让线程2在更改标志之前锁定条件的mutex来修复这种竞争条件。

You should fix this race condition by having thread 2 lock the condition's mutex before changing the flag.

你正在描述一个典型的竞争条件,发生在无保护的标志和条件。这些竞争条件是条件使用中互斥锁模式的原因。

You are describing a typical race condition that happens for unprotected flags and conditions. These race conditions are the reason for the mutex lock pattern in condition usage. Put simply, always have a mutex protect the variables involved in checking a condition value.

在线程2的代码中:

unique_lock<mutex> ul(m);
condition = false;
cv.notify_one();

这篇关于C ++ 11我可以确保condition_variable.wait()不会错过通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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