简体   繁体   English

如何为条件变量等待/通知修复竞争条件

[英]How to fix race condition for condition variable wait/notify

Answer to this question is wrong as it has chance to deadlock. 这个问题的答案是错误的,因为它有可能陷入僵局。 Condition Variable - Wait/Notify Race Condition 条件变量-等待/通知比赛条件

I found no solution to solving race condition or dead lock issue. 我找不到解决竞赛条件或死锁问题的解决方案。

Imagine we have two threads. 想象我们有两个线程。 now goal is as follows. 现在的目标如下。

first condition:
Thread 1 Waits
Thread 2 Notifies

second condition:
Thread 2 Notifies
Thread 1 Should not wait and continue normal execution.

How can this be implemented correctly without having a queue for notifies? 如何在没有通知队列的情况下正确实现呢? because I want this part of code to run as fast as possible and use a Boolean value instead of adding item into queue. 因为我希望这部分代码尽可能快地运行,并使用布尔值而不是将项目添加到队列中。 Also there are only 2 threads, so use of queue seems overkill for me. 而且只有2个线程,所以对我来说使用队列似乎有些过头了。

pseudo code when there is race condition: 存在竞争条件时的伪代码:

Thread 1:
lock(x);
if(!signaled)
{
    unlock(x); // ********
    // still small gap, how to avoid?
    cv.wait(); // forget spurious wakeup for sake of simplicity 
    signaled = false;
}
else // ********
    unlock(x);

Thread 2:
lock(x);
signaled = true;
cv.notify();
unlock(x);

now if you remove two lines commented with ******** race condition will be solved and chance of deadlock will be introduced where Thread1 waits while owning the lock and Thread2 is stuck at locking x. 现在,如果您删除带有注释的两行,则********竞争条件将得到解决,并且死锁的可能性将被引入,其中线程1在拥有锁的同时等待,而线程2卡在锁定x处。

The source of your confusion is your misunderstanding of conditional variables. 混淆的根源是对条件变量的误解。 The inherent feature of them is that lock release and entering into wait mode is done atomically , ie nothing happens in between. 它们的固有特征是锁释放和进入等待模式是原子完成的,即在两者之间什么也没有发生。

So no modification to the variable can be happening before variables enters into wait mode, because lock will not be released. 因此,在变量进入等待模式之前不会对变量进行任何修改,因为不会释放锁定。 This is basic guarantee of any conforming conditional_variable implementation, for example, here is the extract from the reference page for std::conditional_variable : 这是任何符合conditional_variable实现的基本保证,例如,以下是std::conditional_variable的参考页摘录:

http://en.cppreference.com/w/cpp/thread/condition_variable/wait http://en.cppreference.com/w/cpp/thread/condition_variable/wait

Atomically releases lock, blocks the current executing thread, and adds it to the list of threads waiting on *this. 以原子方式释放锁,阻塞当前正在执行的线程,并将其添加到等待* this的线程列表中。 The thread will be unblocked when notify_all() or notify_one() is executed. 执行notify_all()或notify_one()时,该线程将被解除阻塞。 It may also be unblocked spuriously. 它也可能会被虚假地阻止。 When unblocked, regardless of the reason, lock is reacquired and wait exits. 解除阻止后,无论出于何种原因,都将重新获得锁定并等待退出。 If this function exits via exception, lock is also reacquired. 如果此函数通过异常退出,则也将重新获得锁定。 (until C++14) (直到C ++ 14)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM