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

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

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
    评论
线程超时退出是指当一个线程的执行时间超过了预定的时间限制时,线程会自动退出或被强制终止。 在多线程编程中,有时候我们需要限制线程的执行时间,以避免线程的无限等待或导致整个程序的阻塞。为了实现线程超时退出的功能,我们可以采取以下几种方式: 1. 使用定时器:可以在创建线程之后启动一个定时器,在规定时间内检查线程的状态,如果超过了设定的时间限制,就强制终止线程的执行。 2. 使用Thread类提供的join()方法:join()方法允许一个线程等待另一个线程执行完毕。我们可以在创建线程之后,调用join()方法,并设置一个超时时间,如果在超时时间内线程未执行完毕,则认为线程超时退出。 3. 使用信号量或锁机制:可以在创建线程之前设置一个信号量或锁,当线程超时退出时,通过释放或获取信号量或锁来终止线程的执行。 无论采取哪种方式,我们在线程超时退出时,需要注意线程的资源释放和状态的处理。比如,我们可以在线程超时退出时,手动释放线程所占用的资源,如关闭文件、释放内存等;或者可以记录线程超时退出的次数,以便在后续处理中做相应的处理。同时,我们也应该注意避免线程超时退出对整个程序的影响,比如通过设置合理的超时时间、合理分配资源等方式来提高程序的健壮性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值