2
votes

Hello I have an question about cancelling a thread that uses mutexes and conditional variables. The thread has cancel type deferred. When I use only the functions pthread_mutex_lock/unlock and pthread_cond_wait, and a cancel request arrives, the thread's cancelation point is only pthread_cond_wait. Will it lock the mutex or not? I am not sure, if thread always leaves the mutex unlock. Or are the pthread_mutex_lock/unlock functions also cancellation points? Thank you.

3

3 Answers

4
votes

I doubt that I can phrase this better than the documentation:

A condition wait (whether timed or not) is a cancellation point. When the cancelability type of a thread is set to PTHREAD_CANCEL_DEFERRED, a side effect of acting upon a cancellation request while in a condition wait is that the mutex is (in effect) re-acquired before calling the first cancellation cleanup handler. The effect is as if the thread were unblocked, allowed to execute up to the point of returning from the call to pthread_cond_timedwait() or pthread_cond_wait(), but at that point notices the cancellation request and instead of returning to the caller of pthread_cond_timedwait() or pthread_cond_wait(), starts the thread cancellation activities, which includes calling cancellation cleanup handlers.

Also just be sure you are aware that other functions are cancellation points as well.

0
votes

If you have multiple threads waiting on pthread_cond_wait and you call pthread_cancel before sending out some of kind of broadcast using pthread_cond_broadcast or pthread_cond_signal, then it may lead to a deadlock where the pthread_cond_wait is waiting on thread to cancel and thread is waiting on the pthread_cond_wait to come out.

0
votes

Per "The Linux Programming Interface" book pages 667-678 the mutex will be locked. So you can use

pthread_mutex_lock(&mutex);
pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock, &mutex);
while (var == 0)) {
    pthread_cond_wait(&cond, &mutex);
}
pthread_cleanup_pop(1);