Using setInterval() in C++

后端 未结 2 1676
梦毁少年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:56

    There is no built in setInterval in C++. you can imitate this function with asynchronous function:

    template 
    void setInterval(std::atomic_bool& cancelToken,size_t interval,F&& f, Args&&... args){
      cancelToken.store(true);
      auto cb = std::bind(std::forward(f),std::forward(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();
    }
    

提交回复
热议问题