std :: mutex是否公平?

std :: mutex是否公平?

问题描述:

正如问题所述,std::mutex是否公平?即,如果线程A锁定了互斥锁,然后B和C以此顺序在互斥锁上调用了"lock()",那么它们将以相同的顺序获取互斥锁吗?还是未指定该顺序?

As the question states, is std::mutex fair? i.e., if thread A locked the mutex and then B and C call 'lock()' on it in this order, will they obtain the lock on the mutex in this same order or is the order unspecified?

文档根本没有解决这个问题.

The documentation doesn't address this at all.

该标准(第30.4节)没有提及有关互斥体上竞争线程之间的公平性的要求,因此它可能是公平的,也可能是不公平的.

The standard (§30.4) does not mention anything about requirements regarding fairness between contending threads on a mutex, so it might be or might not be fair.

在实践中,std::mutex实现可能会使用其平台提供的任何互斥量实现,这是不公平的,因为这通常更简单,更有效.在Windows上互斥锁通常很公平,但并非总是如此.一些实现例如线程构件块提供了公平的特殊互斥体,但它们不是基于操作系统的本机互斥体,通常实现为自旋锁(具有自己的警告).

In practice std::mutex implementations will probably use whatever mutex implementation their platform provides, which are moslty unfair, as this is usually simpler and more efficient. On windows e.g. mutexes are mostly fair, but not always. Some implementations e.g. Thread Building Block provide special mutexes that are fair, but these are not based on the OSes native mutexes, and are usually implemented as spin-locks (which have their own caveats).