gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:31:56 25 4
gpt4 key购买 nike

我正在做一个项目,该项目需要每 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com