Linux下的线程内的遇\n才会打印
今天创建pthread线程,内部进行调试,发现线程内的\n打印不了的情况。
现象描述:等待十秒钟后,才会打印出一大串的1**2****…集体打印。
#include<pthread.h>
#include<unistd.h>
#include<stdio.h>
void * threadfunc(void *arg){
while(1){
sleep(1);
printf("************2***********");
}
}
int main(int argc, const char *argv[])
{
pthread_t threadid;
pthread_create(&threadid , NULL , threadfunc , NULL);
while(1){
sleep(1);
printf("************1***********");
}
return 0;
}
但是当每条打印信息加入\n以后,就发现会每隔1s打印
************1***********
************2***********
又进行调试发现在线程内多加入几个不带 “\n” 打印信息,最后加入一个"\n"的打印信息,并且每一条打印信息都加入了sleep(1)。发现前面的都会打印出来,经过几秒之后遇到“\n”就会集体打印出来。
不知道是否将数据存入了缓冲区,遇到了"\n"以后才会将数据打印出来,从没有碰到过这种状况。但是之前的程序还是会执行下来。
那么接下来,我使用了流缓冲fflush(stdout)标准输出将数据刷出来
void * threadfunc(void *arg){
while(1){
sleep(1);
printf("************2***********");
fflush(stdout);
}
}
int main(int argc, const char *argv[])
{
pthread_t threadid;
pthread_create(&threadid , NULL , threadfunc , NULL);
while(1){
sleep(1);
printf("************1***********");
fflush(stdout);
}
return 0;
}
哈哈,那么打印数据就被刷出来了。
linux@linux:~/pthread$ g++ 1_pthread_create.cpp -lpthread
linux@linux:~/pthread$ ./a.out
************1***********************2***********************1***********************2***********************1***********************2***********************1***********************2***********************1***********************2***********^C
总结
1.可以通过打印输出语句加入\n
2.使用fflush函数