Linux线程之取消(十三)

Linux线程之取消(十三)

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)

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值