I was reading some code for an exam, and it is something like:
sem_t s;
int main(int argc ,char *argv[]) {
thread_t p1, p2, p3;
sem_init(&s,X,X)
thread_create(&p1,child);
thread_create(&p2,child);
thread_create(&p3,child);
sem wait(&s);
}
How should I initialize semaphore s, assuming that every thread in child has a sem_post() on s, so that the parent concludes his run after three children?
I would say I should initialize it as "sem_init(&s, 1, -2)" so that the 3 sem_posts take it to 1 and the sem_wait doesn't put it to sleep, but still, I think that sem_post wakes a thread up even if the value of the semaphore is less than 0, so, if the parent goes on wait, then the first child to do a sem_post wakes him up and it does not wait for all three children.
I was reading Operating Systems - Three Easy Pieces, and in the concurrency part, when talking about semaphores it does not say that if the value of a semaphore is less than 0 after the increment of a sem_post it does not wake up a thread that is already on a sem_wait, so I assume it in fact does wake it up in any case.
There is no way to initialize
sthat guarantees such behavior from the givenmain(), no matter what the behavior ofchild(). You cannot initializesto a value less than 0. If you initialize it to a value greater than zero thenmain()'s singlesem_wait()does not have to wait for any of the children at all. If you initialize it to 0 thenmain()can proceed as soon as any one of the children performs asem_post().If you want
main()to wait for all three children, each of which increments the semaphore exactly once and never decrements it, then the semaphore must be initialized to 0 andmainmustsem_wait()three times.