views:

109

answers:

4

Does mutex guarantee to execute thread in order of arriving?

that is, if, thread 2 and thread 3 arrive is waiting while thread 1 is in critical section

what exactly happen after thread 1 exit critical section if thread 2 arrive at mutex lock before thread 3, thread 2 will be allowed to enter critical section before thread 3 ?

or race condition will be occurred?

if its not guaranteed, how can i solve this? (maybe queue?)

+3  A: 

That sort of behaviour would have to be an implementation detail of your threading library (which you didn't mention). I would guess most threading libraries don't make any such a guarantee, though. Unless the waiting threads had different priorities, of course.

Carl Norum
Priority Inversion is when a lower priority thread holds shared resources and slows down the higher priority threads.
Romain Hippeau
@Romain, what does that have to do with the question (or my answer)?
Carl Norum
@Carl - With the part about different priority threads holding a resource
Romain Hippeau
+4  A: 

Generally threading libraries do not make any such guarantees, because most OS's don't make any such guarantee. The thread wrapper can't (usually) do any better than the native OS thread management operations.

JSBangs
The good ol' as good as undefined behaviour problem.
TerryP
A: 

It's up to the operating system. In Windows, there is no guaranteed order that any given thread will be awoken and granted the mutex.

JMarsch
A: 

The question you have asked is classical case of "bounded waiting", and there is known way of solving this via [Bakery Algorithm].1

The basic idea here is that you maintain two counts, first is current serving number and other is global count (analogy to a bakery with a running number). Whenever a new thread enters (i.e. waits on a mutex) then increase the global count and give out ticket to the thread. This thread then waits on the ticket number, till the current serving number is equal to ticket number.

This way we can maintain the order such that thread which comes first, gets hold of mutex first.

I am not sure if the standard libraries implement mutex this way internally, but it wouldn't be that difficult to implement Bakery algorithm for your need.

Chintan