2
我有这样并行线程:取消阻塞线程
-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
其中互斥用于同步的情况。工作线程'线程A'和主线程都会进入错误状态,然后设置局部变量'停止',这应该导致线程A被取消并退出主程序。当访问停止(和其他共享对象)时,互斥锁用于防止竞争条件。
不幸的是调用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
}
你有任何想法我可能会尝试别的吗?
预先感谢您