linux - 为什么主线程会将 子线程 已经输出的值再次输出?
本文介绍了linux - 为什么主线程会将 子线程 已经输出的值再次输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
1:
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<errno.h>
void * thread1(void *arg)
{
printf("Hi\n");
}
void * thread2(void *arg)
{
sleep(1);
printf("are you\n");
}
void * thread3(void *arg)
{
sleep(2);
printf("I am pretty good!\n");
}
int main(int argc,char *argv[])
{
pthread_t tid1,tid2,tid3;
if(pthread_create(&tid1,NULL,thread1,NULL) != 0) {
perror("pthread_create");
}
if(pthread_create(&tid2,NULL,thread2,NULL) != 0) {
perror("pthread_create");
}
if(pthread_create(&tid3,NULL,thread3,NULL) != 0) {
perror("pthread_create");
}
//printf("\n"); //如果加入这句就正常了
return 0;
}
2:我的主线程
没有等待任何子线程
,但是现在的执行结果无论如何也不应该像下面这样,把 Hi
输出两次。
3::
解决方案
1) 主线程在子线程执行前关闭了,这个程序就crash了。
2) 我建议你把t2 t3都注释掉,这样肯定不会打印两次。
3) 正确的join/detach
线程也不会出现这样的结果。
这篇关于linux - 为什么主线程会将 子线程 已经输出的值再次输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文