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