1. 程式人生 > >Linux--多執行緒之執行緒的建立和退出

Linux--多執行緒之執行緒的建立和退出

#include "apue.h"
/**
1.main函式的執行緒稱為初始執行緒或主執行緒,主執行緒在main函式返回的時候,會導致
整個程序結束。可以在主執行緒中使用pthread_exit函式 退出主執行緒 如此,
程序會等待所有的執行緒結束時候才終止
*/
struct person{
	int age;
	char name[10];
};

void *thread_fun(void *person1){
	//打印出當前執行緒的ID
	printf("fun thread id=%lu\n", pthread_self());
	printf("age =%d name=%s \n",((struct person*)person1)->age,((struct person*)person1)->name);
	return NULL;
}

 int main(){
	pthread_t tid;
	int err;
	struct person per;
	per.age = 20;
	strcpy(per.name,"liu pan");
	
	//建立執行緒
	err = pthread_create(&tid,NULL,thread_fun,&per);
	if(err!=0){
		perror(" fail to create thread ");
		return -1;
	}
   
	printf("success to create thread tid = %lu \n ",tid);
	//打印出當前執行緒的ID
    printf("main thread id=%lu\n", pthread_self());
	
	//主執行緒退出
	pthread_exit(NULL);//always succeeds
}