长时间睡觉时退出

时间:2016-02-26 17:25:35

标签: c++ c++11

退出此while循环的最简单方法是什么? 是否有某种功能可以检测睡眠时值是否为真? 或者我在循环中设置一个小睡眠并检查退出,如果不再睡觉?如果是这样我该怎么做?

        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));
        }

2 个答案:

答案 0 :(得分:10)

  

是否有某种功能可以检测睡眠时值是否为真?

没有这种方法可以在同一个线程中打破std::this_thread::sleep_for()调用。该线程暂停或多于或少于std::chrono::duration参数中指定的时间。

  

什么是最简单的方法退出这个While循环而它还在睡觉?   或者我在循环中设置一个小睡眠并检查退出,如果不再睡觉?如果是这样我该怎么做?

不要让它睡觉(那么久)。

而不是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 ...

并导致当前线程被暂停。

答案 1 :(得分:3)

您编写的代码实际上对 x 分钟无效;现在你想要它在那段时间做事情(检查一个条件)。你不能双管齐下!

将<{1>}替换为等待条件变量

相关问题