linux环境下pthread中的线程取消

问题描述 投票:0回答:1

我执行了以下示例代码:

#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>

static void * thread_func(void *ignored_argument) {
    int s;

    s = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
    sleep(5);
    s = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

         **while (1);**
         sleep(1000);

    printf("thread_func(): not canceled!\n");
    return NULL;
}

int main(void) {
    pthread_t thr;
    void *res;
    int s;

    s = pthread_create(&thr, NULL, &thread_func, NULL);

    sleep(9);
    printf("main(): sending cancellation request\n");
    s = pthread_cancel(thr);


    s = pthread_join(thr, &res);
    if (res == PTHREAD_CANCELED)
        printf("main(): thread was canceled\n");
    else
        printf("main(): thread wasn't canceled (shouldn't happen!)\n");

    exit(EXIT_SUCCESS);
}

当我注释粗体 while (1) 行(大约第 14 行)时,线程被取消,但是当我取消注释此行时,线程取消不起作用。

据我了解pthread_cancel,取消正在运行和休眠的线程。这样对吗?如果是,请帮助我了解上述代码。

linux 手册页并在 google 中搜索

c linux multithreading pthreads cancellation
1个回答
0
投票

来自

pthread(7)
手册:

取消点

POSIX.1 规定某些函数必须,而某些其他函数必须 函数可能是取消点。如果线程是可取消的, 它的可取消性类型是延迟的,并且取消请求是 等待线程,然后线程在调用时被取消 作为取消点的函数。 以下功能需要作为取消点 POSIX.1-2001 和/或 POSIX.1-2008:

  • 接受()
  • ...
  • 睡觉()

所以

while(1);
不是取消点。

要取消线程而不是取消点,您必须调用

pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
:

pthread_setcanceltype()
设置可取消类型 将线程调用到类型中给定的值。类型参数必须 具有以下值之一:

PTHREAD_CANCEL_DEFERRED

取消请求被推迟到下一个线程 调用一个作为取消点的函数(参见 线程 (7))。这是默认的可取消类型 所有新线程,包括初始线程。

即使延迟取消,取消点也会在 异步信号处理程序仍然可以被执行并且 效果就像异步取消一样。

PTHREAD_CANCEL_ASYNCHRONOUS

线程可以随时取消。 (通常,它 收到取消通知后将立即取消 请求,但系统不保证这一点。)

© www.soinside.com 2019 - 2024. All rights reserved.