为什么主线程会将 子线程 已经输出的值再次输出?

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::图片描述

阅读 3.2k
2 个回答

1) 主线程在子线程执行前关闭了,这个程序就crash了。

2) 我建议你把t2 t3都注释掉,这样肯定不会打印两次。

3) 正确的join/detach线程也不会出现这样的结果。

主要原因是printf在某些系统上不是线程安全的,或者说stdout这个FILE*指针在某些系统不是线程安全的。你看到hi打了两次,有一次并不是第一个线程打的,可能是第二个或者第三个

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题