Using setInterval () in C ++

JavaScript has a function called setInterval(). Can this be done in C ++? If a loop is used, the program does not continue, but continues to call the function.

while(true) {
    Sleep(1000);
    func();
}
cout<<"Never printed";
+4
source share
2 answers

There is no built-in in C ++ setInterval. you can simulate this function using an 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));
     }
  });
}

use cancelTokento cancel interval with

cancelToken.store(false);

notice, however, that this mechanism creates a new thread for the task. It cannot be used for many interval functions. in this case, I would use the already written thread pool with some kind of mechanism for measuring time.

Edit: example use:

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

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

Source: https://habr.com/ru/post/1612401/


All Articles