在C++中使用setInterval()

2g32fytz  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(150)

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

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

qv7cva1a1#

在C++中没有内置的setInterval。你可以用异步函数来模仿这个函数:

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);

但是请注意,此机制为任务构建了一个新线程。它不能用于许多区间函数。在本例中,我将使用已经编写线程池和某种时间测量机制。
Edit:example用途:

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

lo8azlld2#

使用std::thread来实现。

// <thread> should have been included
void setInterval(auto function,int interval) {
    thread th([&]() {
        while(true) {
            Sleep(interval);
            function();
        }
    });
    th.detach();
}
//...
setInterval([]() {
    cout<<"1 sec past\n";
},
1000);

相关问题