pthread_cancel

多线程程序中,终止线程执行的方式有 3 种,分别是:

  1. 线程执行完成后,自行终止;
  2. 线程执行过程中遇到了 pthread_exit() 或者 return,也会终止执行;
  3. 线程执行过程中,接收到其它线程发送的“终止执行”的信号,然后终止执行。

多线程程序中,一个线程还可以向另一个线程发送“终止执行”的信号(后续称“Cancel”信号),这时就需要调用 pthread_cancel() 函数。
参数 thread 用于接收 Cancel 信号的目标线程。如果 pthread_cancel() 函数成功地发送了 Cancel 信号,返回数字 0,否则返回非零数。对于因“未找到目标线程”导致的信号发送失败,函数返回 ESRCH 宏(定义在<errno.h>头文件中,该宏的值为整数 3)。

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>     // sleep() 函数
//线程执行的函数
void * thread_Fun(void * arg) {
    printf("新建线程开始执行\n");
    sleep(10);
}
int main()
{
    pthread_t myThread;
    void * mess;
    int value;
    int res;
    //创建 myThread 线程
    res = pthread_create(&myThread, NULL, thread_Fun, NULL);
    if (res != 0) {
        printf("线程创建失败\n");
        return 0;
    }
    sleep(1);
    //向 myThread 线程发送 Cancel 信号
    res = pthread_cancel(myThread);
    if (res != 0) {
        printf("终止 myThread 线程失败\n");
        return 0;
    }
    //获取已终止线程的返回值
    res = pthread_join(myThread, &mess);
    if (res != 0) {
        printf("等待线程失败\n");
        return 0;
    }
    //如果线程被强制终止,其返回值为 PTHREAD_CANCELED
    if (mess == PTHREAD_CANCELED) {
        printf("myThread 线程被强制终止\n");
    }
    else {
        printf("error\n");
    }
    return 0;
}

79@u10-121-79-98:~/test$ gcc thread.c -o thread.exe -lpthread
c00390379@u10-121-79-98:~/test$ ./thread.exe
新建线程开始执行
myThread 线程被强制终止

posted @ 2023-07-05 14:51  牧 天  阅读(379)  评论(0)    收藏  举报