需要在c ++中以周期性的时间间隔调用函数

编程入门 行业动态 更新时间:2024-10-26 14:29:57
本文介绍了需要在c ++中以周期性的时间间隔调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在c ++中编写一个程序,我需要以周期性的时间间隔调用一个函数,例如每隔10ms。我从来没有做过与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?

谢谢! / p>

Thanks!

推荐答案

一个简单的计时器可以实现如下:

A simple timer can be implemented as follows,

#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) { func(); std::this_thread::sleep_for(std::chrono::milliseconds(interval)); } }).detach(); } void do_something() { std::cout << "I am doing something" << std::endl; } int main() { timer_start(do_something, 1000); while(true); }

这个简单的解决方案没有提供停止计时器的方法。计时器将继续运行,直到程序退出。

This simple solution does not offer a way to stop the timer. The timer will keep running until the program exited.

更多推荐

需要在c ++中以周期性的时间间隔调用函数

本文发布于:2023-11-24 12:26:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625192.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:周期性   间隔   中以   函数   时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!