防止代码中死锁的常见解决方案是确保锁定序列以共同的方式发生,而不管哪个线程正在访问资源.
The common solution to preventing deadlock in code is to make sure the sequence of locking occur in a common manner regardless of which thread is accessing the resources.
例如给定线程 T1 和 T2,其中 T1 访问资源 A,然后 B 和 T2 访问资源 B,然后 A.按需要的顺序锁定资源会导致死锁.简单的解决方案是先锁定 A 再锁定 B,无论特定线程使用资源的顺序如何.
For example given threads T1 and T2, where T1 accesses resource A and then B and T2 accesses resource B and then A. Locking the resources in the order they are needed causes a dead-lock. The simple solution is to lock A and then lock B, regardless of the order specific thread will use the resources.
问题情况:
Thread1 Thread2
------- -------
Lock Resource A Lock Resource B
Do Resource A thing... Do Resource B thing...
Lock Resource B Lock Resource A
Do Resource B thing... Do Resource A thing...
可能的解决方案:
Thread1 Thread2
------- -------
Lock Resource A Lock Resource A
Lock Resource B Lock Resource B
Do Resource A thing... Do Resource B thing...
Do Resource B thing... Do Resource A thing...
我的问题是在编码中使用了哪些其他技术、模式或常见做法来保证防止死锁?
My question is what other techniques, patterns or common practices are used in coding to guarantee dead lock prevention?
您描述的技术不仅很常见:它还是一种已被证明一直有效的技术.不过,在用 C++ 编写线程代码时,您还应该遵循一些其他规则,其中最重要的可能是:
The technique you describe isn't just common: it's the one technique that has been proven to work all the time. There are a few other rules you should follow when coding threaded code in C++, though, among which the most important may be:
我可以继续一段时间,但根据我的经验,使用线程的最简单方法是使用每个可能使用代码的人都熟知的模式,例如生产者/消费者模式:很容易解释,你只需要一个工具(一个队列)就可以让你的线程相互通信.毕竟,两个线程相互同步的唯一原因是允许它们进行通信.
I could go on for a while, but in my experience, the easiest way to work with threads is using patterns that are well-known to everyone who might work with the code, such as the producer/consumer pattern: it's easy to explain and you only need one tool (a queue) to allow your threads to communicate with each other. After all, the only reason for two threads to be synchronized with each other, is to allow them to communicate.
更一般的建议:
#include <thread>
#include <cassert>
#include <chrono>
#include <iostream>
#include <mutex>
void
nothing_could_possibly_go_wrong()
{
int flag = 0;
std::condition_variable cond;
std::mutex mutex;
int done = 0;
typedef std::unique_lock<std::mutex> lock;
auto const f = [&]
{
if(flag == 0) ++flag;
lock l(mutex);
++done;
cond.notify_one();
};
std::thread threads[2] = {
std::thread(f),
std::thread(f)
};
threads[0].join();
threads[1].join();
lock l(mutex);
cond.wait(l, [done] { return done == 2; });
// surely this can't fail!
assert( flag == 1 );
}
int
main()
{
for(;;) nothing_could_possibly_go_wrong();
}
这篇关于防止代码死锁的锁定策略和技术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!