我正在練習線程編程,並發現這一點。當我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");
}
可能duplacte的http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin – hyde