1. 程式人生 > >執行緒只被建立呼叫一次

執行緒只被建立呼叫一次

#include<stdio.h>
#include"common.h"

pthread_once_t once=PTHREAD_ONCE_INIT;
pthread_once_t once2=PTHREAD_ONCE_INIT;

void fun2_run(){

	while(1){
		printf("I am fun 2...\n");sleep(1);

	}

}

void *fun2(){
//fun2_run();
	pthread_once(&once2,fun2_run);
}
void fun_run(){

	pthread_t pthid;
	pthread_create(&pthid,NULL,fun2,NULL);
	while(1){

		printf("I am fun\n");sleep(1);

	}
}

void *fun(){
//fun_run();
	pthread_once(&once,fun_run);
}


int main()
{

	pthread_t pthid;
	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);pthread_join(pthid,NULL);}
		else if(i==1){pthread_create(&pthid,NULL,fun,NULL);}
		else printf("input not 1 && 0\n");
	}
}