简体   繁体   English

std::scoped_lock 和互斥锁排序

[英]std::scoped_lock and mutex ordering

I'm trying to determine if std::scoped_lock tries to establish an ordering or mutex id to acquire locks in a prescribed order.我正在尝试确定std::scoped_lock 是否尝试建立一个排序或互斥 ID 以按规定的顺序获取锁。 Is not clear to me that it does it from a somewhat brief looking at a browsable implementation I found googling around .我不清楚它是否是通过对我在谷歌搜索中发现的可浏览实现的稍微简短的了解来实现的

In case it is not doing that, What would be the closest to standard implementation of acquiring an ordered set of locks?如果它不这样做,那么最接近获取有序锁集的标准实现的是什么?

Typically the cleanest way to avoid deadlocks is to always acquire a group of locks in the same order (and yes, sure, always release them all before trying to acquire new locks again, but perhaps 2PL is a little beyond the scope of what std::scoped_lock should aim to do)通常避免死锁的最干净的方法是始终以相同的顺序获取一组锁(是的,当然,在尝试再次获取新锁之前总是释放它们,但也许 2PL 有点超出标准的 scope std::scoped_lock应该旨在做)

The order for std::lock isn't defined until run-time, and it is not fixed. std::lock的顺序直到运行时才定义,并且不固定。 It is discovered experimentally by the algorithm for each individual call to std::lock .它是通过算法针对每次对std::lock的单独调用通过实验发现的。 The second call to std::lock could lock the mutexes in a different order than the first, even though both calls might use the same list of mutexes in the same order at the call site.std::lock的第二次调用可能会以与第一次不同的顺序锁定互斥锁,即使这两个调用可能在调用站点以相同的顺序使用相同的互斥锁列表。

Here is a detailed performance analysis of several possible implementations of std::lock : http://howardhinnant.github.io/dining_philosophers.html下面是对std::lock的几种可能实现的详细性能分析: http://howardhinnant.github.io/dining_philosophers.html

Using a fixed ordering of the mutexes is one of the algorithms that is performance-compared in the above link.使用固定顺序的互斥量是上述链接中进行性能比较的算法之一。 It is not the best performing algorithm for the experiments conducted.对于所进行的实验,它不是性能最好的算法。

The libstdc++ implementation the OP points to is a high quality implementation of what the analysis labels "Smart & Polite" OP 指向的libstdc++ 实现分析标签“智能和礼貌”的高质量实现

scoped_lock 's constructor is stated to call std::lock on its mutexes, so its behavior is governed by this function. And std::lock is specifically defined to avoid deadlocks on what it locks. scoped_lock的构造函数被声明为在其互斥量上调用std::lock ,因此其行为受此 function 的约束。并且std::lock被专门定义为避免在其锁定的内容上发生死锁。 The order it locks the mutexes in is undefined, but it won't result in a deadlock.它锁定互斥量的顺序未定义,但不会导致死锁。

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

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