1

我面临一个与 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 仍在工作并且线程正在终止。任何帮助将不胜感激

4

1 回答 1

4

pthread_setcancelstate设置调用线程的可取消类型,即您的情况下的主线程。因此,如果您想让新创建的线程不可取消,您应该从该线程的上下文中调用该函数。

见 man 3 pthread_setcancelstate

请注意,虽然 Linux pthreads 实现允许 NULLoldstate指针,但是 POSIX 并没有指定,因此最好为oldsate.

于 2012-10-23T14:26:59.737 回答