互斥锁是否可以保证采集的顺序? [英] Do mutexes guarantee ordering of acquisition?
问题描述
一个同事最近遇到了一个问题,归结为我们认为具有两个线程的C ++应用程序中的以下事件序列:
A coworker had an issue recently that boiled down to what we believe was the following sequence of events in a C++ application with two threads:
-
线程A拥有一个互斥锁.
Thread A holds a mutex.
当线程A持有互斥量时,线程B试图锁定它.由于线程B被保留,因此将被挂起.
While thread A is holding the mutex, thread B attempts to lock it. Since it is held, thread B is suspended.
线程A完成了持有互斥量的工作,从而释放了互斥量.
Thread A finishes the work that it was holding the mutex for, thus releasing the mutex.
此后不久,线程A需要触摸受互斥锁保护的资源,因此它将再次锁定它.
Very shortly thereafter, thread A needs to touch a resource that is protected by the mutex, so it locks it again.
似乎再次为线程A提供了互斥锁;线程B仍在等待,即使它首先请求"该锁.
It appears that thread A is given the mutex again; thread B is still waiting, even though it "asked" for the lock first.
此事件序列是否符合C ++ 11的std::mutex
和/或pthreads的语义?老实说,我以前从未考虑过互斥的这一方面.
Does this sequence of events fit with the semantics of, say, C++11's std::mutex
and/or pthreads? I can honestly say I've never thought about this aspect of mutexes before.
推荐答案
已知问题. C ++互斥体是OS提供的互斥体之上的薄层,而OS提供的互斥体通常是不公平的.他们不在乎FIFO.
Known problem. C++ mutexes are thin layer on top of OS-provided mutexes, and OS-provided mutexes are often not fair. They do not care for FIFO.
同一枚硬币的另一面是,线程通常不会抢占,直到线程用完它们的时间片.结果,在这种情况下,线程A可能会继续执行,并因此立即获得了互斥锁.
The other side of the same coin is that threads are usually not pre-empted until they run out of their time slice. As a result, thread A in this scenario was likely to continue to be executed, and got the mutex right away because of that.
这篇关于互斥锁是否可以保证采集的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!