zoukankan      html  css  js  c++  java
  • 关于子线程执行两次的问题

    #include<pthread.h>
    #include<stdio.h>
    
    pthread_t ntid;
    void printids(const char *s)
    {
        pid_t pid;
        pthread_t tid;
        pid = getpid();
        tid = pthread_self();
        printf("%s pid %lu tid %lu (0x%lx)
    ",s,(unsigned long)pid,
                (unsigned long)tid,(unsigned long)tid);
    }
    
    void * thr_fn(void *arg)                                                                                                                   
    {
        printids("new thread:");
        return ((void *)0);
    }
    
    int main(int argc, const char *argv[])
    {
        int err;
        err = pthread_create(&ntid,NULL,thr_fn,NULL);
        if(err !=0)
        {
            perror("erro");
           return 0;
        }
    
        printids("main thread:");
    //  sleep(1);
        return 0;
    }
    

      在运行时会出现3中情况:

    1.

    main thread: pid 4815 tid 3075843776 (0xb755a6c0)
    new thread: pid 4815 tid 3075840832 (0xb7559b40)
    

    2.

    main thread: pid 4800 tid 3076433600 (0xb75ea6c0)
    

    3.

    main thread: pid 4773 tid 3075663552 (0xb752e6c0)
    new thread: pid 4773 tid 3075660608 (0xb752db40)
    new thread: pid 4773 tid 3075660608 (0xb752db40)
    

    第一种情况可以理解为:主线程先运行,正要退出的时候,子线程运行了

    第二种情况可以理解为:主线程运行完了,并结束了进程,这时子线程还没来的及运行。

    第三种情况理解:答案是从网上找到的:https://segmentfault.com/q/1010000003739810?sort=created

    首先,这个程序是错误的,在exit()的时候会在stdout上发生竞争。
      你要明白,发生竞争之后出现什么情况都不稀奇,所以不要深究这个原因了,没有意义,这跟stdio的实现相关。

      举个可能的场景满足你的好奇心,比如:
      新线程的printf在写完缓冲区之后执行flush——调用write,再要把已经write过的数据从缓冲区中删掉,但是在删除之前,main线程的exit也要flush stdout,就可能把已经flush过          的数据又flush了一遍。

  • 相关阅读:
    [POI2005]A Journey to Mars 单调队列
    滑动窗口 单调队列
    逆序对 模拟贪心
    迷宫 dfs爆搜
    [Usaco2019 Feb]The Great Revegetation
    [Usaco2007 Dec]挑剔的美食家
    [HNOI2004]宠物收养所
    bzoj2639 矩形计算
    [Ahoi2013]作业
    Gty的二逼妹子序列
  • 原文地址:https://www.cnblogs.com/jiaan/p/9557430.html
Copyright © 2011-2022 走看看