我有这样的情况
-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其中互斥锁用于同步。工作线程'Thread A‘和主线程都可以进入错误状态,然后设置本地变量'Stop’,这应该会导致取消线程A并退出主程序。Mutex用于防止在访问Stop (和其他共享对象)时出现争用情况。
不幸的是,当目标线程等待互斥时,调用pthread_cancel()似乎不起作用:
#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
}你知道我还会尝试别的什么吗?
提前谢谢你
发布于 2013-04-26 05:05:35
pthread_mutex_lock()显然不是pthread_cancel()可以取消线程的取消点;如果确实需要中断线程,则需要找到一种方法来释放它正在等待的互斥锁,以便它可以到达取消点(或者,好吧,不在需要取消线程的区域中使用互斥锁)。
摘自pthread_cancel()手册;
pthread_mutex_lock()不是一个取消点,尽管它可能会无限期地阻塞;使pthread_mutex_lock()成为一个取消点将使编写正确的取消处理程序变得困难,如果不是不可能的话。
https://stackoverflow.com/questions/16224469
复制相似问题