muffel
muffel

Reputation: 7360

pthreads: cancel blocking thread

I have a situation like

 -Thread A-

 Lock Mutex
 If ActionA() == ERROR
    Stop = True
 Unlock Mutex

 -Mainthread-

 Lock Mutex
 If ActionB() == ERROR
    Stop = True
 If Stop == True
    Cancel ThreadA
    Join ThreadA
    Exit program
 Unlock Mutex

where a Mutex is used for synchronization. The worker thread 'Thread A' and the main thread can both get into an error state and set the local variable 'Stop' then, which should lead to the cancellation of Thread A and exit of the main program. The Mutex is used to prevent a race condition when accessing Stop (and other shared objects).

Unfortunately calling pthread_cancel() does not seem to work when the target thread is waiting for a Mutex:

#include <pthread.h>

pthread_mutex_t mutex;

void *thread(void *args){
    pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL);
    pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
    pthread_mutex_lock(&mutex);
    return NULL;
}

int main(int argc, const char * argv[])
{
    pthread_mutex_init(&mutex, NULL);
    pthread_mutex_lock(&mutex);
    pthread_t t;
    pthread_create(&t, NULL, thread, NULL);
    pthread_cancel(t);
    pthread_join(t, NULL);
    //Execution does not get here
}

Do you have any idea what I might try else?

Thank you in advance

Upvotes: 2

Views: 4470

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 180867

pthread_mutex_lock() is just plain not a cancellation point where pthread_cancel() can cancel the thread; if you really need to break the thread, you need to find a way to release the mutex it's waiting for so it can reach a cancellation point (or, well, not use mutexes in the regions where it needs to be cancelled).

From the pthread_cancel() manual;

pthread_mutex_lock() is not a cancellation point, although it may block indefinitely; making pthread_mutex_lock() a cancellation point would make writing correct cancellation handlers difficult, if not impossible.

Upvotes: 3

Related Questions