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

标签 c++ timer

我正在做一个项目,该项目需要每 1 分钟 重置一个变量,而不会暂停 无限循环

例如:

int temp = 0;

while(true){

temp ++;

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

}

如何在 C++ 中实现这一点?

感谢您的帮助!

最佳答案

    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

虽然 sleep 循环可能会被优化掉。

关于c++ - 在无限循环中每 60 秒重置一次变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43817586/

相关文章:

安卓NDK : Static library used is different than precompiled library specified

c++ - 从 pcl::PointCloud<pcl::PointXYZRGB> 中删除点

c# - System.Threading.Timer 和在 C# 中创建自己的后台滴答线程之间有什么区别

c - 如何在 Windows 或 Linux 中查找 C 函数的运行时间

.net - 检测是否调用了垃圾收集器(.Net)

java - onStop() 方法中的空指针异常

c++ - 标准流打印无关字符

c++ - c++中的sqlite3创建语句和外键

c++ - 有没有办法将 OpenCV 中的 minAreaRect 与 double 一起使用?

c# - 未将对象引用设置为对象实例(计时器数组)