2 winsbb winsbb 于 2017.09.01 10:18 提问

Linux线程分离后主线程连接怎么会成功? 1C

源代码如下:
#include
#include
#include
void *thread1(void *arg);
void *thread2(void *arg);
void main(){
int err1,err2;
pthread_t tid1,tid2;
void *retval1,*retval2;
//pthread_create()成功返回0
err1 = pthread_create(&tid1,NULL,thread1,NULL);
err2 = pthread_create(&tid2,NULL,thread2,NULL);
printf("main thread begin\n");
if(err1 || err2){
printf("create thread err\n");
return 0;
}
//pthread_join()成功返回0,否则返回错误码
printf("th1 join state:%d\n",pthread_join(tid1,&retval1));
printf("th2 join state:%d\n",pthread_join(tid2,&retval2));
printf("th1 return val:%d\n",(void *)retval1);
printf("th2 return val:%d\n",(void *)retval2);
printf("main thread end\n");
}

void *thread1(void *arg){
printf("hello I am thread1\n");
return (void *)1;
}
void *thread2(void *arg){
printf("hello I am thread2\n");
pthread_detach(pthread_self());
return (void *)2;
}

运行结果:
第二幅图为什么会运行正常?线程分离后连接不是会失败的吗?
图片说明

图片说明

Csdn user default icon
上传中...
上传图片
插入图片