需要精确的线程睡眠.最大 1ms 误差

2021-12-08 00:00:00 multithreading sleep loops winapi c++

我有运行循环的线程.我需要该循环每 5 毫秒运行一次(1 毫秒错误).我知道 Sleep() 函数不精确.

您有什么建议吗?

更新.我不能以其他方式做到这一点.在循环结束时,我需要某种睡眠.我也不想 100% 加载 CPU.

解决方案

从问题标签来看,我猜你是在 Windows 上.看看多媒体计时器,他们宣传精度低于 1 毫秒.另一种选择是使用 Spin Locks 但这基本上会使 CPU 核心保持最大使用率.

I have thread that runs loop. I need that loop to be run once every 5ms (1ms error). I know that Sleep() function is not precise.

Do you have any suggestions?

Update. I can't do it other way. At the end of loop I need some kind of Sleep. I don't want to have 100% CPU loaded either.

解决方案

From the question tags I suppose you are on windows. Take a look at Multimedia Timers, they advertise precision under 1ms. Another options is to use Spin Locks but this will basically keep a cpu core at maximum usage.

相关文章