Windows环境下C语言如何限制循环速度或调整线程优先级
解决方案
1. 替换轮询逻辑从根本降低CPU占用
当前代码的死循环全程轮询时间判断逻辑会持续占用CPU资源,是CPU占用高的核心原因。此外代码中使用的clock()函数统计的是进程的CPU运行耗时,并非真实墙上时间,计算得到的1ms间隔和实际时间存在偏差。
最优解决方案是使用系统提供的睡眠函数让线程在等待间隔期间让出CPU,休眠期间完全不占用CPU资源,修改后CPU占用率可降至接近0,且时间精度更高:
#include <stdio.h> #include <time.h> #include <pthread.h> #include <errno.h> #include <unistd.h> #include <sys/syscall.h> int CL; void *driveClock(void *vargp){ struct timespec ts; // 使用单调时钟,不受系统时间修改影响 clock_gettime(CLOCK_MONOTONIC, &ts); while(1){ CL++; // 计算下一次1ms后的触发时间 ts.tv_nsec += 1000000; if (ts.tv_nsec >= 1000000000) { ts.tv_sec += 1; ts.tv_nsec -= 1000000000; } // 休眠到指定时间,被信号中断时自动重试 int ret; do { ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL); } while (ret == EINTR); } } int main(){ pthread_t thread_id; pthread_create(&thread_id, NULL, driveClock, NULL); pthread_join(thread_id,NULL); return 0; }
2. 调整线程优先级(辅助优化)
如果必须保留原轮询逻辑,可以通过调低线程优先级避免该线程抢占其他重要任务的CPU资源,注意调整优先级不会降低该程序的总CPU占用,仅会改变系统的调度优先级。
普通调度策略下可以通过调整nice值降低优先级,nice值范围为-20到19,值越大优先级越低:
// 在线程函数开头调用 #include <sys/resource.h> setpriority(PRIO_PROCESS, syscall(SYS_gettid), 19);
如果需要使用实时调度策略(需要root权限),可以通过pthread接口设置:
// 在线程函数开头调用 struct sched_param param = { .sched_priority = 10 // 实时优先级范围1-99,值越大优先级越高 }; pthread_setschedparam(pthread_self(), SCHED_RR, ¶m);
内容的提问来源于stack exchange,提问作者theboringkid
相关产品推荐
相关产品推荐

