开发者

Wait & Signal order

If the following pieces of code execute in the order in which I have put them, can I be sure that thread 1 is awoken first by thread 3, later followed by thread 2?

main:
sem_init(&x,0,0);

thread 1:
sem_开发者_StackOverflowwait(&x);

thread 2:
sem_wait(&x);

thread 3:
sem_post(&x);


There is no reason to make such an assumption. It depends on when thread 1 and thread 2 are invoquing sem_wait(), i.e., on what they do before and how the scheduler gives them CPU for running. If you want that thread 1 be awoken before thread 2, you need another semaphore:

main:
sem_init(&x,0,0);
sem_init(&y,0,0);

thread 1:
sem_wait(&x);
sem_post(&y);

thread 2:
sem_wait(&y);

thread 3:
sem_post(&x);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜