c++笔记(线程的退出和取消)

本文介绍了三种在C++中不终止进程情况下退出线程的方式:线程函数返回、使用pthread_exit函数和通过其他线程取消。着重讲解了pthread_exit函数的工作原理以及线程取消的机制,包括取消点的概念。
摘要由CSDN通过智能技术生成

可以通过以下三种方式在不终止进程的情况下退出线程

1 线程从执行函数中返回

2 线程调用pthread_exit 函数退出

3 线程可以被同一进程的其它线程取消

#include<pthread.h>
void pthread_exit(void *retval);
/*
功能   退出线程,一个进程中的多个线程是共享该进程中的数据段,因此,通常线程退出后所占用的资源并
       不会释放
参数    retval 存储线程退出状态的指针
返回    无
*/


// pthread_exit1.c

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


void *func1(void *arg){

	int i=0;
	for(i=0;i<5;i++){
		printf("func1 %d\n",i);
		sleep(1);
	}

	//这两句都是退出线程,这样写是等价的
	pthread_exit(NULL);
	//return NULL;

	// 这句会退出整个程序
	//exit(0);
}


int main(){

	int ret=-1;
	pthread_t tid=-1;
	
	pthread_create(&tid,NULL,func1,NULL);

	printf("press any key quit\n");
        getchar();

	return 0;
}

// 编译 gcc pthread_exit1.c -pthread -o pthread_exit1
// 运行 .pthread_exit1   不贴图了
// 

线程取消

#include<pthread.h>
int pthread_cancel(pthread_t thread);
/*
功能  杀死(取消)线程
参数  thread  目标线程ID
返回  成功 0     失败  -1

线程取消并不是实时的,而是有一定延时,需要等待线程达到某个取消点,类似于游戏中的存档,必须到达某个
指定场所(仓库,城里 等)才能存储进度,杀死线程也不是立刻就能完成,必须要达到取消点。

取消点 是线程检查是否被取消,并按请求进行动作的一个位置,通常是一些系统调用 如 create,open,pause
       等,(man 7 pthreads 可查看全部) 可粗略的认为一个系统调用(进入内核)即为一个取消点.

*/


// pthread_cancel.c

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


void *func1(void *arg){

        int i=0;
        for(i=0;i<5;i++){
                printf("func1 %d\n",i);
                sleep(1);
        }

        pthread_exit(NULL);


}


int main(){

        int ret=-1;
        pthread_t tid=-1;

        pthread_create(&tid,NULL,func1,NULL);

        sleep(3);
        printf("sleep 3s cancel\n");
        pthread_cancel(tid);

        return 0;

}

// 编译 gcc pthread_cancel.c -pthread -o pthread_cancel
// 运行 ./pthread_cancel   结果如下
// 

发布于 2021-01-15 21:24

c++笔记(线程的退出和取消) - 知乎 (zhihu.com)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值