<pthread.h>
头文件中,语法格式如下:
int pthread_cancel(pthread_t thread);参数 thread 用于指定发送 Cancel 信号的目标线程。
<errno.h>
头文件中,该宏的值为整数 3)。对于接收 Cancel 信号后结束执行的目标线程,等同于该线程自己执行如下语句:注意,pthread_cancel() 函数的功能仅仅是向目标线程发送 Cancel 信号,至于目标线程是否处理该信号以及何时结束执行,由目标线程决定。我们会在《终止线程执行,这个坑千万别踩!》一节给您做详细讲解。
pthread_exit(PTHREAD_CANCELED);也就是说,当一个线程被强制终止执行时,它会返回 PTHREAD_CANCELED 这个宏(定义在
<pthread.h>
头文件中)。#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; }假设程序编写在 thread.c 文件中,执行过程为:
[root@localhost ~]# gcc thread.c -o thread.exe -lpthread
[root@localhost ~]# ./thread.exe
新建线程开始执行
myThread 线程被强制终止
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有