2

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

4

1 回答 1

3

pthread_mutex_lock()只是简单的不是pthread_cancel()可以取消线程的取消点;如果您确实需要中断线程,则需要找到一种方法来释放它正在等待的互斥锁,以便它可以到达取消点(或者,在需要取消的区域中不要使用互斥锁)。

来自pthread_cancel()手册;

pthread_mutex_lock() 不是取消点,尽管它可能会无限期地阻塞;使 pthread_mutex_lock() 成为取消点将使编写正确的取消处理程序变得困难,如果不是不可能的话。

于 2013-04-25T21:05:35.097 回答