为什么这些printfs表现不同?

时间:2016-07-12 15:56:52

标签: c multithreading printf

我正在练习线程编程并找到了这个。当我printf("1")时,输出将在几秒后出现,但是当我printf("\n")时,输出将逐步进行。为什么呢?

#include<stdio.h>
#include<pthread.h>
#include<errno.h>
#include<stdlib.h>



void * __th_handle(void *);

int run_now=0;      // globle var

int main()
{
    char message[]={"going in thread"};
    void * th_result;
    int ret,c=0;
    pthread_t __th;


//  printf("in main thread\n"); 

    if(pthread_create(&__th,NULL,(void *)__th_handle,(void *)message)==-1)
        {
        perror("pthread_creat fails ");
        exit(0);
        }

    while(c++<20)
    {
        if(run_now==0)
            {
            printf("1");    //printf("1\n");
            run_now=1;
            }
        else
            {sleep(1);}
    }


    pthread_join(__th,&th_result);
    if(ret!=0)
    {
    perror("join fails");
    exit(0);
    }   
    printf("th_result from __th thread : %s\n",(char *)th_result);  

return 0;
}

void * __th_handle(void *argv)
{
//  printf("message : %s",(char *)(argv));
    int c1=0;
    while(c1++<20)
    {
        if(run_now==1)
            {
            printf("2");    //printf("2\n");
            run_now=0;
            }
        else
            {sleep(1);}
    }


    sleep(2);
    pthread_exit("_th thread terminated");

}

2 个答案:

答案 0 :(得分:1)

默认情况下,stdout的输出是行缓冲的。

如果添加换行符,则每个printf()都会产生自己的输出。

如果您不添加换行符,则会累积输出,直到看到换行符或程序结束。这通常会产生单个输出。

答案 1 :(得分:1)

FILE*具有不同的缓冲模式。通常stdout是行缓冲的,这意味着输出仅在有换行符时打印,或者显式调用fflush(stdout)

有3种缓冲模式:

  • unbuffered
  • 行缓冲
  • 完全缓冲

您可以详细了解不同的缓冲如何工作以及如何更改它here

相关问题