I have two semaphores x (initially at 1) , and y (initially at 0).
My thread function code is somewhat like this:
...
wait(x);
//setting some vars
signal(x);
wait(y);
...
I want to ensure that the threads wait on y in line, ie. if the first thread completed the x-guarded section first, it should get to wait on y first, & so on. In the current implementation, a context switch occuring after signal(x); can prevent this from happening.
Is there a way to do this, or do I have to restructure the code completely to prevent this eventuality?
Unfortunately, semaphores and all other POSIX locking tools don’t allow to set priorities or similar to regulate the order in which they are obtained. (This is not a bug but a feature.-)
The easiest way to accomplish the task you want is to protect a state variable by a
pthread_mutex_tand a correspondingpthread_cond_t. In the state variable you could implement a simple timestamp to keep track of the order in which the threads passed through the protected section. Something like