线程只被创建调用一次

#include <stdio.h>
#include "../common.h"
 
pthread_once_t once = PTHREAD_ONCE_INIT;

void cleanup(void *argv)
{
	char *abc = (char*)argv;
	delete abc;
	cout<<"-------------hhh----------"<<endl;
}


void fun_run()
{
	char *abc = new char[1000*1000*100*2]();
 	int i = 0;
	pthread_cleanup_push(cleanup,abc); //push与pop组成函数对,在此期间退出都会调用指定的(这里是cleanup)函数去清理
	while(1)
	{
		printf("I am fun (i = %d)\n",i++);
		sleep(1); 
	}
	pthread_cleanup_pop(0);
}
 
void *fun(void *)
{
	printf("*******************\n");
	pthread_once(&once,fun_run);//设置函数只能被执行一次,但是fun会被执行多次
	printf("$$$$$$$$$$$$$$$$$4$$\n");
}
 
 
int main()
{ 
	pthread_t pthid = 0;
	pthread_attr_t attr;
	pthread_create(&pthid,NULL,fun,NULL);
	
	int i;
	while(1)
	{
		printf("I am main...input a num...\n");
		scanf("%d",&i);
		getchar();
		if(i == 0)
		{
			pthread_cancel(pthid);
			pthid = 0;
			//pthread_join(pthid,NULL); //设置为分离的线程是不能调用pthread_join的,调用后可能会出错
			//pthread_attr_destroy (&attr);
		}
		else if(i == 1)//测试是否会一直创建
		{
			//if(pthid > 0)pthread_cancel(pthid);
			pthread_attr_init(&attr);
			pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);//设置分离属性	
			pthread_create(&pthid,&attr,fun,NULL);
		}
		else 
		{
			printf("input not 1 && 0\n");
		}
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值