Using setInterval() in C++

后端 未结 2 1637
梦毁少年i
梦毁少年i 2021-02-06 16:13

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.

相关标签:
2条回答
  • 2021-02-06 16:43

    Use std::thread to achieve.

    // <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 讨论(0)
  • 2021-02-06 16:56

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

    use cancelToken to cancel the interval with

    cancelToken.store(false);
    

    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.

    Edit : example use:

    int main(int argc, const char * argv[]) {
        std::atomic_bool b;
        setInterval(b, 1000, printf, "hi there\n");
        getchar();
    }
    
    0 讨论(0)
提交回复
热议问题