std::scoped_lock 和互斥排序

std::scoped_lock and mutex ordering

我正在尝试确定是否 std::scoped_lock tries to establish an ordering or mutex id to acquire locks in a prescribed order. Is not clear to me that it does it from a somewhat brief looking at a browsable implementation I found googling around

如果它不这样做,最接近获取有序锁集的标准实现的是什么?

通常避免死锁的最干净的方法是始终以相同的顺序获取一组锁(是的,当然,在尝试再次获取新锁之前总是释放它们,但也许 2PL 有点超出了std::scoped_lock 的目标范围)

scoped_lock 的构造函数被声明为在其互斥量上调用 std::lock,因此其行为受此函数控制。并且 std::lock is specifically defined 以避免在它锁定的内容上出现死锁。它锁定互斥量的顺序未定义,但不会导致死锁。

std::lock 的顺序直到 运行 时才定义,并且不固定。它是通过算法对每个对 std::lock 的单独调用通过实验发现的。对 std::lock 的第二次调用可能会以与第一次不同的顺序锁定互斥锁,即使这两个调用可能在调用站点以相同的顺序使用相同的互斥锁列表。

下面是std::lock几种可能实现的详细性能分析:http://howardhinnant.github.io/dining_philosophers.html

使用固定顺序的互斥量是上述link中进行性能比较的算法之一。对于所进行的实验,它不是性能最好的算法。

libstdc++ implementation the OP points to is a high quality implementation of what the analysis 标签“聪明且有礼貌”