Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of execution of waiting threads blocked by mutex

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?

like image 403
void Avatar asked Oct 09 '09 17:10

void


People also ask

Does thread wait for mutex lock?

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.

Does mutex block the thread?

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.

What happens when a thread is waiting?

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.

Is mutex lock blocking?

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.


1 Answers

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.

like image 98
Remus Rusanu Avatar answered Nov 14 '22 22:11

Remus Rusanu