在无限循环中每60秒重置一次变量值

时间:2017-05-06 06:45:05

标签: c++ timer

我正在开展一个项目,需要每1 Minute重置变量而不暂停infinite loop

例如:

int temp = 0;

while(true){

temp ++;

//After 60 Seconds
call_to_a_function(temp);
temp = 0;

}

如何在C++中实现这一目标?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

    atomic_int  temp;

    std::thread t( [&temp]()
                  {

                      while( temp!= -1){
                          std::this_thread::sleep_for(std::chrono::seconds(60));
                          temp=0;
                      }
                  });


    while ( true )
    {
        temp < INT_MAX ? temp++ : 0;
        cout << temp << endl;
    }
    // do some stuff
    // when program needs to exit, do this to avoid a crash

    temp = -1; // t will exit the loop
    t.join();  // wait until t finishes running

虽然带睡眠的循环可能会被优化掉。