C++实现代码段100ms执行超时后暂停100ms续行的方案咨询
问题:C++实现带执行时长控制的循环执行逻辑
需求说明:
- 实现循环执行逻辑,为目标代码段分配100ms的执行时长
- 若代码段未在100ms内执行完毕,暂停100ms后继续执行该代码段剩余部分,循环此流程
此前尝试使用sleep类方法时遇到的问题:这类方法会先暂停指定时长再执行代码,导致总耗时为「暂停时长+执行时长」,无法匹配需求。
以下是尝试的测试代码:
#include<iostream> #include<stdio.h> #include<thread> #include<windows.h> int ms=0, sec=0, mins=0; void timerms(){ while(true){ ms++; if(ms==80){ // should be 1000 for ms sec++; if(sec==60){ mins++; sec=0; } ms=0; } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } int main(){ //timer thread std::thread t1(timerms); //Thread for printing std::thread t2([](){ while(true){ //printf("%d ms\t\t%d sec\t\t%d mins\n", ms, sec, mins); std::cout<<ms<<" ms\t\t"<<sec<<"sec\t\t"<<mins<<"mins"<<std::endl; } }); t1.join(); t2.join(); return 0; }
解决方案
核心思路是先执行代码段,再根据实际执行时长控制流程:用高精度时钟记录执行起始时间,确保代码段每次执行不超过100ms;若未完成任务,则暂停100ms后继续执行剩余部分。
示例实现代码:
#include <iostream> #include <chrono> #include <thread> // 模拟可能超过100ms的长任务,通过progress记录执行进度 void long_running_task(int& progress, int total_steps) { if (progress < total_steps) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); // 模拟单步耗时 progress++; std::cout << "Task progress: " << progress << "/" << total_steps << std::endl; } } int main() { const std::chrono::milliseconds exec_window(100); // 单次执行时长上限 const std::chrono::milliseconds pause_duration(100); // 暂停时长 int task_progress = 0; const int total_task_steps = 50; // 任务总步数 while (task_progress < total_task_steps) { auto start_time = std::chrono::high_resolution_clock::now(); // 执行目标代码段,直到耗尽100ms或任务完成 while (task_progress < total_task_steps) { auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - start_time ); if (elapsed >= exec_window) break; // 已用满分配时长,暂停 long_running_task(task_progress, total_task_steps); } // 任务未完成则触发暂停 if (task_progress < total_task_steps) { std::cout << "Reached 100ms execution limit, pausing for 100ms..." << std::endl; std::this_thread::sleep_for(pause_duration); } } std::cout << "Task completed!" << std::endl; return 0; }
代码说明:
- 用
std::chrono::high_resolution_clock实现高精度计时,准确控制执行时长 - 内层循环确保目标代码段单次执行不超过100ms
- 外层循环处理暂停逻辑,任务未完成时暂停100ms后继续执行剩余部分
- 通过
progress变量跟踪任务进度,支持分段执行长任务
内容的提问来源于stack exchange,提问作者Bhavesh Vishwakarma
相关产品推荐
相关产品推荐

