我正面临一个与pthread_cancel相关的问题。请参阅以下代码:
void* func(void *arg)
{
while(1)
{
sleep(2);
}
}
#include<stdlib.h>
#include <stdio.h>
#include <pthread.h>
int main()
{
void *status;
pthread_t thr_Var;
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
pthread_create(&thr_Var,NULL,func,NULL);
pthread_cancel(thr_Var);
pthread_join(thr_Var,&status);
return 0;
}
我怀疑即使我禁用了取消状态,仍然pthread_cancel正在工作并且线程正在终止。 任何帮助将不胜感激
答案 0 :(得分:4)
pthread_setcancelstate
设置调用线程的可取消性类型,即您的案例中的主线程。因此,如果您想让新创建的线程不可取消,您应该在该线程的上下文中调用该函数。
见man 3 pthread_setcancelstate
注意虽然Linux pthreads实现允许NULL oldstate
指针,但POSIX没有指定,因此最好为oldsate
提供指针。 / p>