linux - 为什么主线程会将 子线程 已经输出的值再次输出?
阿神
阿神 2017-04-17 15:32:08
[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::

阿神
阿神

闭关修行中......

全部回复(2)
阿神

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

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

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

PHP中文网

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号