如何仅使用C ++ 11永久睡眠 [英] How to sleep forever only using C++11
问题描述
是的,我可以在Windows中使用Sleep()或在POSIX中使用pause(),然后继续。
但是如何仅使用C ++ 11进行睡眠?我认为有一种方法,可以使用std :: this_thread加入调用线程,但与pthread函数不同,std :: this_thread没有join()方法。
更不用说我们不能使用C ++ 11处理信号,而且我知道如何像下面这样永远迭代睡眠:
Yes, I could use Sleep() in Windows or pause() in POSIX, and goes on. But how do I sleep only using C++11? I thought there was a way, which is joining calling thread using std::this_thread but std::this_thread has no join() method unlike pthread functions. Not to mention that we can't handle signals with C++11 and I know how to iterate sleep forever like below:
while(true)
std::this_thread::sleep_for(std::chrono::seconds(1));
但是,正如您所看到的,它一点也不优雅。这段代码仍然消耗CPU时间。调度程序必须照顾这个过程。我也可以使用条件变量或promise,但是再一次它会占用一些内存或无法在某些操作系统上运行(它将抛出异常以避免死锁)。
However, as you can see, It's not elegant at all. This code still consumes CPU time. The scheduler has to care for this process. I could also use conditional variable or promise, but then again it takes up a bit of memory or wouldn't work on certain OS(it would throw an exception to avoid deadlock).
也许这等效于Windows的Sleep(INFINITE):
Maybe this could be the equivalent of Sleep(INFINITE) of Windows:
while(true)
std::this_thread::sleep_for(std::chrono::hours::max());
但是很多人说这不切实际。
But many say it's not practical.
有人能想到出色的方法吗?
Could anyone think of brilliant way?
推荐答案
我可以想到两种方法。
一个,@ Guiroux提到的是 sleep_until
不可到达的时间:
One, which @Guiroux mentions is to sleep_until
a non-reachable time:
std::this_thread::sleep_until(std::chrono::system_clock::now() + std::chrono::hours(std::numeric_limits<int>::max()));
或者让它无限期地等待永远不会满足的条件。
Or have it wait indefinitely for a condition that will never be fulfilled.
std::condition_variable cv;
std::mutex m;
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, []{return false;});
但是我看不出原因。
这篇关于如何仅使用C ++ 11永久睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!