gpt4 book ai didi

c++ - 长时间 sleep 时退出

转载 作者:太空狗 更新时间:2023-10-29 23:29:57 27 4
gpt4 key购买 nike

while 循环仍在休眠时退出它的最简单方法是什么?是否有某种函数可以在 sleep 时检测某个值是否为真?
或者我是否在循环中设置一个小 sleep 并检查如果不再睡一会儿就退出?如果可以,我该怎么做?

        std::atomic<bool> _execute;

while (_execute.load(std::memory_order_acquire))
{
//do stuff

//How to exit druing this long sleep
std::this_thread::sleep_for(std::chrono::minutes(_Delay));
}

最佳答案

Is there some kind of function that can detect if a value is true while sleeping?

不,没有这样的方法来打破std::this_thread::sleep_for()在同一个线程中调用。线程挂起的时间或多或少在 std::chrono::duration 中指定争论。

Whats the easiest way to exit this While loop while its still sleeping?
Or do I set up a small sleep in a loop and check to exit if not sleep some more? if so how would I do that?

根本不要让它休眠(那么久)。

而不是 sleep_for()您可以使用条件变量和 wait_for() 用于发出退出循环的信号(来自另一个线程)。


正如您在 comment 中阐明的那样,而不是使用 std::atomic<bool>您应该重新组织一下代码(再次使用条件变量):

#include <iostream>
#include <chrono>
#include <thread>
#include <condition_variable>
#include <mutex>

const std::chrono::seconds MainDelay = std::chrono::seconds(5);
const std::chrono::seconds WorkerTimeResolution = std::chrono::seconds(2);
std::mutex cv_m;
std::condition_variable cv;
bool _execute = false;

void worker_thread() {
std::unique_lock<std::mutex> lk(cv_m);
while (cv.wait_for(lk,WorkerTimeResolution,[](){return _execute ;})) {
// do stuff as long _execute is true,
// may be with more varying timing conditions than sleep_for() ...
std::cout << "Worker thread executing ..." << std::endl;
std::this_thread::sleep_for(WorkerTimeResolution);
}
}

int main() {
std::thread t(worker_thread);
_execute = true;
cv.notify_all();

for(int i = 0; i < 3; ++i) {
// Do other stuff, may be with more varying timing conditions ...
std::this_thread::sleep_for(MainDelay);
std::cout << "Main thread executing ..." << std::endl;
}
_execute = false;
cv.notify_all();
t.join();
}

Online Demo


请注意,有许多可能的操作而不是 std::this_thread::sleep_for() , 这可能在

中同步
// Do stuff ...

并导致当前线程被挂起。

关于c++ - 长时间 sleep 时退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35658000/

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