简体   繁体   中英

WaitForSingleObject - do threads waiting form a queue?

如果我设置3个线程来等待释放互斥锁,它们是否根据它们请求的顺序形成队列,或者它是未定义的行为(即我们不知道哪个将首先获取它)?

It is explicitly documented in the SDK article :

If more than one thread is waiting on a mutex, a waiting thread is selected. Do not assume a first-in, first-out (FIFO) order. External events such as kernel-mode APCs can change the wait order.

These kind of events are entirely out of your control. So "undefined behavior" is an appropriate way to describe it.

The Mutex Object is mostly fair. The APC case can occur but it is not that common. Especially if the thread is not doing I/O or is doing I/O using completion ports or synchronously.

Most of the Windows user-mode locks (SRWLock, CriticalSection) are unfair if you can acquire them without blocking but fair if you have to block in the kernel. The reason it is done this way is to avoid lock convoys. The moment a fair lock becomes contended, every acquirer has to go through the scheduler and the context switch path before getting the lock. No one can 'skip ahead' and just take the lock because they happen to be running. Thus the lock acquire time for the last thread in the queue increases by the scheduling and context switch time for each prior thread in the queue. The system does not recover from this state until external load is mostly removed because this is a stable condition.

For performance, I would recommend using one of the aforementioned user-mode locks since they are much faster than a kernel mutex, if they fit into your scenario.

There seem to be very mixed opinions about this and no clear information anywhere. In this thread: http://us.generation-nt.com/answer/are-events-fair-help-38447612.html some people seem to suggest that fairness of events is implemented using a simple fifo queue that ignores priorities, while others are saying that fairness should not be assumed.

Bottom line, I think you're better off not basing your logic on fairness, or wrapping an event with your own implementation that guarantees fairness.

Yes, only one thread will be wake up and lock mutex. But order is undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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