pthread_cancel

2021-08-12  本文已影响0人  糖鸡丝

1.pthread_cancel

pthread_cancel()函数不是直接使得线程退出,而是在系统调用中设置一个cancelpoint,当有系统调用函数的时候就会检查是有设置了这个cancelpoint,如果设置了那么就退出线程,相反不退出。

代码举例:

static void* pthread_func1(void* arg)
{
    while(1)
    {
        printf("haha\n");
        sleep(1);
    }
    return NULL;
}
static void* pthread_func2(void* arg)
{
    int a = 0;
    for( ;; )
        a++;
    return NULL;
}

int main(int argc, char const *argv[]) {
    pthread_t tid;
    pthread_create(&tid, NULL, pthread_func1, NULL);
    #pthread_create(&tid, NULL, pthread_func2, NULL);

    pthread_cancel(tid);
    pthread_join(tid, NULL);
    return 0;
}

当调用为pthread_func1时,会走到sleep(系统调用)时,退出线程;
而当调用为pthread_func2时,将会一直循环下去,因为没有触发系统调用。
系统调用常见:man page for syscalls

上一篇下一篇

猜你喜欢

热点阅读