4- pthread其他接口

参考:https://blog.csdn.net/u010383937/article/details/78215287

https://www.cnblogs.com/lijunamneg/archive/2013/01/25/2877211.html

 

phtread_join():监控等待线程结束,阻塞接口。类似进程的wait()

pthread_cancel():需要设置被取消线程取消使能、取消类型(延迟、异步)。然后在自己线程里取消该线程

 

1- phtread_join():监控等待线程结束,阻塞接口。类似进程的wait()

pthread_exit():线程自行退出,类似进程的exit()

示例:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<pthread.h>

void * thread_strat(void *message)
{
    printf("%s[%d] %s thread=%lu \n",__func__,__LINE__,(const char *)message,pthread_self());
	
	sleep(1);
	printf("%s[%d] thread=%lu  here is thread\n",__func__,__LINE__,pthread_self());
	
	/*线程自行退出:return、pthread_exit*/
	pthread_exit(NULL);
	//return message;
}

int main(void)
{
	pthread_t thread;
	int ret;
	const char *message = "creat thread succ";
	
	/*只是创建线程,并不执行*/
	ret = pthread_create(&thread,NULL,thread_strat,(void *)message);
	if(!ret)
	{
		perror("pthread_creat");
	}
	printf("%s[%d] thread=%lu \n",__func__,__LINE__,pthread_self());
	
	/*等待线程thread结束,期间自己阻塞挂起。当thread结束后才返回*/
	pthread_join(thread,NULL);
	printf("%s[%d] i'm comming!\n",__func__,__LINE__);

	return 0;
}

 

2-  线程取消和清理

pthread_cancel():需要设置被取消线程取消使能、取消类型(延迟、异步)。然后在自己线程里取消该线程

pthread_cleanup_push/pop():释放线性资源

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<pthread.h>

void * thread_strat(void *message)
{
    printf("%s[%d] %s thread=%lu \n",__func__,__LINE__,(const char *)message,pthread_self());
	
	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);//PTHREAD_CANCEL_DEFERRED
	
	while(1)
	{
		printf("%s[%d] thread=%lu  here is thread\n",__func__,__LINE__,pthread_self());
	}
	
	
	/*线程自行退出:return、pthread_exit*/
	pthread_exit(NULL);
	//return message;
}

int main(void)
{
	pthread_t thread;
	int ret;
	const char *message = "creat thread succ";
	
	/*只是创建线程,并不执行*/
	ret = pthread_create(&thread,NULL,thread_strat,(void *)message);
	if(!ret)
	{
		perror("pthread_creat");
	}
	
	printf("%s[%d] thread=%lu \n",__func__,__LINE__,pthread_self());
	
	/*取消线程*/
	pthread_cancel(thread);	
	printf("%s[%d] i'm comming!\n",__func__,__LINE__);

	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值