need to call a function at periodic time intervals in c++(需要在 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)
;
}
这篇关于需要在 C++ 中以周期性的时间间隔调用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:需要在 C++ 中以周期性的时间间隔调用一个函数


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09