std :: mutex是否公平? [英] Is std::mutex fair?

查看:129
本文介绍了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).

这篇关于std :: mutex是否公平?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆