怎么在while循环设置超出时间后跳出?

orangepolly 2014-08-22 09:10:41
while(ri_u0c1 != 1)
这样有时候等几秒接收到数据后就跳出了
有时候收不到数据就一直等下去,想要实现等待10秒后,如果还是没有收到数据就跳出,怎么实现啊
...全文
4454 11 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
码农很疯狂 2018-06-26
  • 打赏
  • 举报
回复

#ifdef WIN32
#include <windows.h>
void sleep_ms(int ms) {
Sleep(ms);
}
#else
#include <unistd.h>
void sleep_ms(int ms) {
usleep(ms*1000);
}
#endif
int count=0;
while (ri_u0c1 != 1) {
//...
sleep_ms(50);
count++;
if (count>200) break;
}

max_min_ 2014-08-22
  • 打赏
  • 举报
回复
select函数用下
zilaishuichina 2014-08-22
  • 打赏
  • 举报
回复
引用 3 楼 orangepolly 的回复:
是R8C的程序 GetTickCount报错啊
那就找你能用的 取系统时间的函数
盘子饿了 2014-08-22
  • 打赏
  • 举报
回复
引用 1 楼 zilaishuichina 的回复:

	int lastTick = GetTickCount();
	int currTick = lastTick;
	while(ri_u0c1 != 1 && (currTick - lastTick) < (10/*秒*/ * 1000))
	{
		//...
		currTick = GetTickCount();
	}
这样写的话在循环时CPU会占满的吧,至少应该在循环之中sleep一下。
orangepolly 2014-08-22
  • 打赏
  • 举报
回复
看不懂啊,不会用 我是菜鸟一枚
阿麦 2014-08-22
  • 打赏
  • 举报
回复
更好的实现方法是用 WaitForSingleObject(handle, 10000); 当handle接到信号,或等待时间超过10秒,会继续执行下面的语句。
orangepolly 2014-08-22
  • 打赏
  • 举报
回复
GetTickCount' value is undefined
orangepolly 2014-08-22
  • 打赏
  • 举报
回复
是R8C的程序 GetTickCount报错啊
brookmill 2014-08-22
  • 打赏
  • 举报
回复
t1 = 获取系统时间(); while(ri_u0c1 != 1 && 获取系统时间() - t1 < 10) linux里面是用time(),不记得windows用什么了
zilaishuichina 2014-08-22
  • 打赏
  • 举报
回复

	int lastTick = GetTickCount();
	int currTick = lastTick;
	while(ri_u0c1 != 1 && (currTick - lastTick) < (10/*秒*/ * 1000))
	{
		//...
		currTick = GetTickCount();
	}
赵4老师 2014-08-22
  • 打赏
  • 举报
回复 1
#ifdef WIN32
#include <windows.h>
void sleep_ms(int ms) {
    Sleep(ms);
}
#else
#include <unistd.h>
void sleep_ms(int ms) {
    usleep(ms*1000);
}
#endif
int count=0;
while (ri_u0c1 != 1) {
    //...
    sleep_ms(50);
    count++;
    if (count>200) break;
}

65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧