I have a mutex that controls access to a single object from multiple threads. When a thread has finished the mutex is unlocked to allow order threads to operate on the object. On Windows using the WaitForSingleObject function is there an order that threads are signaled? I want the first thread that attempts to lock the mutex to now be allowed to lock the mutex. This would be a FIFO queue so that signaling to the blocked threads is not random. Would I have to implement my own queuing mechanism to achieve this? And if so what functions are useful?
Mutexes are used to protect shared resources. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it.
If the mutex is already locked by another thread, the subroutine blocks the calling thread until the mutex is unlocked. If the mutex is already locked by the calling thread, the subroutine might block forever or return an error depending on the type of mutex.
A thread is in the waiting state when it wants to wait on a signal from another thread before proceeding. Once this signal is received, it becomes runnable. A thread moves to the blocked state when it wants to access an object that is being used (locked) by another thread.
mutex::lock Locks the mutex. If another thread has already locked the mutex, a call to lock will block execution until the lock is acquired.
FIFO signaling leads to lock convoys. On newer versions of the Win32 API the convoy issue is addressed by macking mutexes and other synchrnonization primitives explicitly unfair (ie. no FIFO).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With