需要在 C++ 中以周期性的时间间隔调用一个函数
我正在用 C++ 编写一个程序,我需要以周期性的时间间隔调用一个函数,比如每 10 毫秒左右.我从未在 C++ 中做过与时间或时钟相关的任何事情,这是一个快速简便的问题,还是没有巧妙解决方案的问题?
I am writing a program in c++ where I need to call a function at periodic time intervals, say every 10ms or so. I've never done anything related to time or clocks in c++, is this a quick and easy problem or one of those where there is no neat solution?
谢谢!
推荐答案
为了完成这个问题,@user534498 的代码可以很容易地调整为具有周期性的滴答间隔.只需要在定时器线程循环开始时和sleep_until
执行函数后确定下一个开始时间点.
To complete the question, the code from @user534498 can be easily adapted to have the periodic tick interval.
It's just needed to determinate the next start time point at the beginning of the timer thread loop and sleep_until
that time point after executing the function.
#include <iostream>
#include <chrono>
#include <thread>
#include <functional>
void timer_start(std::function<void(void)> func, unsigned int interval)
{
std::thread([func, interval]()
{
while (true)
{
auto x = std::chrono::steady_clock::now() + std::chrono::milliseconds(interval);
func();
std::this_thread::sleep_until(x);
}
}).detach();
}
void do_something()
{
std::cout << "I am doing something" << std::endl;
}
int main()
{
timer_start(do_something, 1000);
while (true)
;
}
相关文章