线程安全退出或取消

在线程运行中,很有可能被其他线程使用pthread_cancel()函数取消掉,如果取消线程后还有互斥锁没有解锁,那么就会造成死锁状态。使用pthread_cleanup_push(handler, NULL)函数和pthread_cleanup_pop()函数可以避免死锁情况发生

1、相关API函数原型
在这里插入图片描述
在这里插入图片描述
注意:
1、如果线程退出时没有返回值,则设置为NULL
2、pthread_join()指定的进程如果还在运行,则将阻塞等待
3、pthread_tryjoin_np()指定的线程还在运行,则立即返回出错返回

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.例子:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <pthread.h>

pthread_mutex_t m;

void handler(void *arg)
{
	pthread_mutex_unlock(&m);
	
}

void *Routine(void *arg)
{
//	pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);		//取消线程功能disable,pthread_cancel()无效
		
	pthread_cleanup_push(handler, NULL);	//加锁前,将handler函数压入贤臣取消处理例程的栈中,以防中途线程被取消,当线程被取消是执行handler函数
	
	pthread_mutex_lock(&m);
	printf("tid1 printf\n");
	sleep(5);								//延迟5秒为了等待main线程取消线程tid1
	pthread_mutex_unlock(&m);
		
	pthread_cleanup_pop(0);					//将handler函数从栈中弹出,但不执行handler函数	
	
	pthread_exit("routine exit");			//正常退出,并返回"routine exit"
}

int main(int argc, void *argv[])
{
	pthread_mutex_init(&m, NULL);
	
	pthread_t tid1;	
	pthread_create(&tid1, NULL, Routine, NULL);
	
	sleep(1);
	
	pthread_cancel(tid1);					//取消线程tid1
	
	pthread_mutex_lock(&m);
	printf("main printf\n");
	pthread_mutex_unlock(&m);
	
//	void *p;
//	pthread_join(tid1, &p);					//阻塞等待子线程tid1退出,并获取子线程返回值
//	printf("tid1 exit receive:%s\n", (char *)p );
	
	pause();
	
	exit(0);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值