pthread conditions and process termination pthread conditions and process termination multithreading multithreading

pthread conditions and process termination


It seems that the p2 process is waiting on the conditional variable eternally since the p1 process has no chance to send a notification being terminated by ctrl-c. As you and other people have already mentioned pthread conditional variable does not "know" about its original process termination.

If you cannot use another inter process communication features and still insist on shared mutex and conditional variable, I would think about trapping the signal.


The source code of pthread_cond_destroy says the following:

Thus, we can assume that all waiters that are still accessing the condvar have been woken. We wait until they have confirmed to have woken up by decrementing __wrefs.

So we can simply reset __wrefs to zero before pthread_cond_destroy:

c->c.__data.__wrefs = 0;r = pthread_cond_destroy(&c->c);

I ran you sample with this change and P1 completes with no hang.

Note that before this commit __wrefs was called __nwaiters.


One more option might be the explicitly call pthread_ond_broadcast() before calling pthread_cond_destroy().

Like this:

r = pthread_cond_broadcast(&c->c);puts("Before pthread_cond_destroy");r = pthread_cond_destroy(&c->c);printf("After pthread_cond_destroy, r=%d\n", r);r = pthread_mutex_destroy(&c->m);printf("After pthread_mutex_destroy, r=%d\n", r);