#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)\n",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了一遍。

 

posted on 2018-08-29 22:39  子都  阅读(436)  评论(0编辑  收藏  举报