1.线程取消
int pthread_cancel(pthread_t thread);
功能:
杀死(取消)线程。
参数:
thread : 目标线程ID。
返回值:
成功:0
失败: 出错编号。
注意:线程的取消并不是实时的,而又一定的延时。需要等待线程到达某个取消点(检查点)。 类似于玩游戏存档,必须到达指定的场所(存档点,如:客栈、仓库、城里等)才能存储进度。 杀死线程也不是立刻就能完成,必须要到达取消点。 取消点:是线程检查是否被取消,并按请求进行动作的一个位置。通常是一些系统调用creat,open,pause,close,read,write… 执行命令man 7 pthreads可以查看具备这些取消点的系统调用列表。 可粗略认为一个系统调用(进入内核)即为一个取消点。
2.参考代码
//=============================================================================
// File Name : thread_cancel.c
// Author : FengQQ
//
// Description : 线程取消
// Annotation : 取消tid指定的线程,成功返回0,但是取消只是发送一个请求,
// 并不意味着等待线程终止,而且发送成功;也不意味着tid一定会终止。
//
// Created by FengQQ. 2020-10-04
//=============================================================================
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
void *pthread_callback(void *arg)
{
while(1)
{
pthread_testcancel(); //设置取消点
}
return 0;
}
int main(int argc,char *argv[])
{
int ret;
int cval,jval;
pthread_t ptid;
ret = pthread_create(&ptid,NULL,pthread_callback,NULL);
if(ret != 0)
{
printf("create new pthread failed...\r\n");
return -1;
}
sleep(3);
cval = pthread_cancel(ptid);
if(cval != 0)
{
printf("pthread cancel failed...\r\n");
}
printf("pthread cancel success\r\n");
jval = pthread_join(ptid,NULL);
if(jval != 0)
{
printf("pthread join failed...\r\n");
}
printf("pthread join success\r\n");
return 0;
}
Linux线程间通信之信号量(十九)
链接: link.(https://blog.csdn.net/qq_39721016/article/details/120604654?spm=1001.2014.3001.5501)