Linux下的线程内的遇\n才会打印该怎么办

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函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值