开发者

Semaphore Syncing

开发者 https://www.devze.com 2023-01-20 22:33 出处:网络
I have two semaphores x (initially at 1) , and y (initially at 0). My thread function code is somewhat like this:

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 ther开发者_开发百科e 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_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;
};


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.


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消