在JavaScript中,有一个函数叫做setInterval()
。用C++可以实现吗?如果使用循环,程序不会继续,而是继续调用该函数。
while(true) {
Sleep(1000);
func();
}
cout<<"Never printed";
没有内置的setInterval
在C++中。你可以用异步函数来模仿这个函数:
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));
}
});
}
use cancelToken
取消间隔
cancelToken.store(false);
但请注意,该机制为该任务构造了一个新线程。它不适用于许多区间函数。在这种情况下,我将使用已经编写的线程池和某种时间测量机制。
编辑:示例使用:
int main(int argc, const char * argv[]) {
std::atomic_bool b;
setInterval(b, 1000, printf, "hi there\n");
getchar();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)