#include "apue.h"
/**
1.main函数的线程称为初始线程或主线程,主线程在main函数返回的时候,会导致
整个线程结束。可以在主线程中使用pthread_exit函数 退出主线程 如此,
进程会等待所有的线程结束时候才终止
当一个线程被pthread_join之后 另外一个线程不能再pthread_join它
*/
struct person{
int age;
char name[10];
};
void *thread_fun(void *person1){
int i;
for(i=0;i<5;i++){
printf("fun1 age =%d name=%s \n",((struct person*)person1)->age,((struct person*)person1)->name);
sleep(1);
}
printf(" fun 1 ended\n");
return (void *)1;
}
void *thread_fun2(void *person1){
int i;
for(i=0;i<5;i++){
printf("fun2 age =%d name=%s \n",((struct person*)person1)->age,((struct person*)person1)->name);
sleep(2);
}
printf(" fun 2 ended\n");
return (void *)2;
}
int main(){
pthread_t tid1,tid2;
int err1,err2;
//初始化结构体1
struct person per;
per.age = 20;
strcpy(per.name,"liu pan");
//初始化结构体2
struct person per2;
per2.age = 18;
strcpy(per2.name,"li si");
//创建线程
err1 = pthread_create(&tid1,NULL,thread_fun,&per);
err2 = pthread_create(&tid2,NULL,thread_fun2,&per2);
if(err1||err2){//err1或者err2不等于0时
perror(" fail to create thread ");
return -1;
}
printf("success to create thread err1 =%d err2 =%d\n ",err1,err2);
printf("pid1 = %lu tid2 = %lu \n",tid1,tid2);
//连接线程
void *rval,*rval2;
pthread_join(tid1,&rval);
pthread_join(tid2,&rval2);
printf("rval = %d rval2 = %d \n",(int)rval,(int)rval2);//打印线程函数返回值
printf("start to quit main thread \n ");
//主线程退出
pthread_exit(NULL);//always succeeds
}
Linux--多线程之线程连接pthread_join
最新推荐文章于 2024-09-18 21:19:33 发布