在JavaScript中,有一个名为setInterval()的函数。可以用C++实现吗?如果使用循环,程序不会继续,而是继续调用函数。
setInterval()
while(true) { Sleep(1000); func(); } cout<<"Never printed";
qv7cva1a1#
在C++中没有内置的setInterval。你可以用异步函数来模仿这个函数:
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
cancelToken.store(false);
但是请注意,此机制为任务构建了一个新线程。它不能用于许多区间函数。在本例中,我将使用已经编写线程池和某种时间测量机制。Edit:example用途:
int main(int argc, const char * argv[]) { std::atomic_bool b; setInterval(b, 1000, printf, "hi there\n"); getchar(); }
lo8azlld2#
使用std::thread来实现。
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);
2条答案
按热度按时间qv7cva1a1#
在C++中没有内置的
setInterval
。你可以用异步函数来模仿这个函数:使用
cancelToken
取消间隔但是请注意,此机制为任务构建了一个新线程。它不能用于许多区间函数。在本例中,我将使用已经编写线程池和某种时间测量机制。
Edit:example用途:
lo8azlld2#
使用
std::thread
来实现。