0

I'm practicing threaded programing and found this. When I printf("1"), the output will comes after a few seconds, but when I printf("\n"), the output comes step-by-step. Why?

#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
    Possible duplacte of http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin – hyde Jul 12 '16 at 16:26

2 Answers2

1

The output for stdout is line buffered by default.

If you add a newline, every printf() will cause own output.

If you do not add a newline, the output will be accumulated until a newline is seen or the program ends. This will typically result in a single output.

schily
  • 297
  • 1
  • 5
1

The FILE* has different buffering modes. Typically stdout is line buffered, which means that the output is only printed when there is a newline, or if you explicitly calls fflush(stdout)

There are 3 buffering modes :

  • unbuffered
  • line buffered
  • fully buffered

You can read more about how the different buffering works and how to change it here

Soren
  • 13,623
  • 4
  • 34
  • 66