views:

40

answers:

3

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?

A: 

If this is important to you, then you indeed have to restructure the code.

To my knowledge, there is no guarantee that, when a semaphore gets signaled, the waiting processes would be woken up in the order in which they started waiting.

Ideally, your processes should not care in which order they reach the synchronization point and in which order they continue processing.

Bart van Ingen Schenau
+1  A: 

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_t and a corresponding pthread_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

struct state {
 pthread_mutex_t mutex;
 pthread_cond_t cond;
 size_t seen_at_x;
 size_t seen_at_y;
};
Jens Gustedt
A: 

I don't know if this will work! it does not allow to cancel a thread synch/asynch but i don't know if it works for context-switch between threads. try putting:

pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL)

and after the last line when you are done with it:

pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL)
Green Code