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
}
你有任何想法我可能會嘗試別的嗎?
預先感謝您