gpt4 book ai didi

c++ - 如何理解 C++ Concurrency in Action 中同一类的实例导致死锁问题?

转载 作者:行者123 更新时间:2023-11-28 01:41:51 31 4
gpt4 key购买 nike

我正在阅读 C++ Concurrency in Action ,并遇到以下描述 deadlock 的语句(第 47 ~ 48 页):

The common advice for avoiding deadlock is to always lock the two mutexes in the same order: if you always lock mutex A before mutex B, then you’ll never deadlock. Sometimes this is straightforward, because the mutexes are serving different purposes, but other times it’s not so simple, such as when the mutexes are each protecting a separate instance of the same class. Consider, for example, an operation that exchanges data between two instances of the same class; in order to ensure that the data is exchanged correctly, without being affected by concurrent modifications, the mutexes on both instances must be locked. However, if a fixed order is chosen (for example, the mutex for the instance supplied as the first parameter, then the mutex for the instance supplied as the second parameter), this can backfire: all it takes is for two threads to try to exchange data between the same two instances with the parameters swapped, and you have deadlock!

我对以下部分的含义很困惑:

However, if a fixed order is chosen (for example, the mutex for the instance supplied as the first parameter, then the mutex for the instance supplied as the second parameter), this can backfire: all it takes is for two threads to try to exchange data between the same two instances with the parameters swapped, and you have deadlock!

前面提到“一个操作”,然后提到“两个线程尝试交换数据”。作者想表达的实际场景是什么?

最佳答案

这是指这样的情况:

你有一个函数

void foo(bar& a, bar& b) {
lock_guard<mutex> lock1(a.mutex);
...
lock_guard<mutex> lock2(b.mutex);
}

乍一看,这似乎遵循了始终以相同顺序锁定互斥量的建议。

如果你有

bar a, b;

foo 可以被称为

foo(a, b);

在一个线程中,作为

foo(b, a);

在另一个。然后,你就会陷入僵局。

关于c++ - 如何理解 C++ Concurrency in Action 中同一类的实例导致死锁问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46827642/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com