背景
某天客户反馈程序cpu占用99%,要求分析出问题,经排查发现是由于nanosleep函数使用不当导致
代码模拟
#include <time.h>
#include <stdio.h>
int count;
void do_printbuf()
{
count++;
printf("do print buf called %d\n",count);
}
int main()
{
struct timespec s_time,ostime;
s_time.tv_sec = 0;
s_time.tv_nsec = 1000 * 1000 * 1000;//故障行
//s_time.tv_nsec = 10 *1000*1000;
while(1)
{
do_printbuf();
printf("tv_nsec %ld,sizeof %d\n",s_time.tv_nsec,sizeof s_time.tv_sec);
nanosleep(&s_time,&ostime);//故障行
}
return 0;
}
编译执行后输出结果
do print buf called 47938
tv_nsec 1000000000,sizeof 8
do print buf called 47939
tv_nsec 1000000000,sizeof 8
do print buf called 47940
tv_nsec 1000000000,sizeof 8
do print buf called 47941
tv_nsec 1000000000,sizeof 8
do print buf called 47942