Semaphores waiting for child threads

31 views Asked by At

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.

1

There are 1 answers

0
John Bollinger On

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?

There is no way to initialize s that guarantees such behavior from the given main(), no matter what the behavior of child(). You cannot initialize s to a value less than 0. If you initialize it to a value greater than zero then main()'s single sem_wait() does not have to wait for any of the children at all. If you initialize it to 0 then main() can proceed as soon as any one of the children performs a sem_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 and main must sem_wait() three times.