在C ++中使用setInterval() [英] Using setInterval() in C++

查看:195
本文介绍了在C ++中使用setInterval()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,有一个名为 setInterval()的函数。可以在C ++中实现吗?如果使用循环,程序不会继续,但会继续调用该函数。

In JavaScript, there is a function called setInterval(). Can it be achieved in C++? If a loop is used, the program does not continue but keeps calling the function.

while(true) {
    Sleep(1000);
    func();
}
cout<<"Never printed";


推荐答案

setInterval 。你可以用异步函数模仿这个函数:

There is no built in setInterval in C++. you can imitate this function with asynchronous function:

template <class F, class... Args>
void setInterval(std::atomic_bool& cancelToken,size_t interval,F&& f, Args&&... args){
  cancelToken.store(true);
  auto cb = std::bind(std::forward<F>(f),std::forward<Args>(args)...);
  std::async(std::launch::async,[=,&cancelToken]()mutable{
     while (cancelToken.load()){
        cb();
        std::this_thread::sleep_for(std::chrono::milliseconds(interval));
     }
  });
}

使用 cancelToken 取消间隔

cancelToken.store(false);

请注意,这个mchanism构造一个新的任务线程。它不能用于许多间隔函数。在这种情况下,我将使用已编写的线程池和某种时间测量机制。

do notice though, that this mchanism construct a new thread for the task. it is not usable for many interval functions. in this case, I'd use already written thread-pool with some sort of time-measurment mechanism.

编辑:example use:

Edit : example use:

int main(int argc, const char * argv[]) {
    std::atomic_bool b;
    setInterval(b, 1000, printf, "hi there\n");
    getchar();
}

这篇关于在C ++中使用setInterval()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆