Reputation:
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_wait(&x);
thread 2:
sem_wait(&x);
thread 3:
sem_post(&x);
Upvotes: 1
Views: 824
Reputation: 67831
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);
Upvotes: 1