2016-07-12 41 views
0

我正在练习线程编程,并发现这一点。当我printf("1"),输出将在几秒钟后出现,但当我printf("\n"),输出一步一步。为什么?为什么这些printfs的行为不同?

#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"); 

} 
+1

可能duplacte的http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin – hyde

回答

1

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

如果添加换行符,则每个printf()都将导致自己的输出。

如果不添加换行符,输出将被累计,直到看到换行符或程序结束。这通常会导致单个输出。

+0

谢谢你是对的! –

1

FILE*有不同的缓冲模式。典型地,标准输出行缓冲,这意味着当有一个新行,或者如果显式调用fflush(stdout)

有3种缓冲器模式时输出时,才会打印:

  • 无缓冲
  • 行缓冲
  • 全缓冲

你可以阅读更多关于如何在不同的缓冲工作以及如何去改变它here