How to sleep forever only with C ++ 11

Yes, I can use Sleep () on Windows or pause () on POSIX and continue. But how can I only sleep using C ++ 11? I thought there was a way that connects a thread call using std :: this_thread, but std :: this_thread does not have a join () method, unlike pthread functions. Not to mention the fact that we cannot process signals with C ++ 11, and I know how to repeat sleep forever, as shown below:

while(true) std::this_thread::sleep_for(std::chrono::seconds(1)); 

However, as you can see, this is far from elegant. This code still consumes CPU time. The planner must take care of this process. I could also use a conditional variable or promise, but then again it takes up some memory or will not work on a specific OS (it would choose an exception to avoid a deadlock).

Perhaps this could be the equivalent of Sleep (INFINITE) Windows:

 while(true) std::this_thread::sleep_for(std::chrono::hours::max()); 

But many say that is impractical.

Can anyone think of a brilliant path?

+6
source share
3 answers

There are two ways that I can think of.

One that @Guiroux mentions in sleep_until not an achievable time:

 std::this_thread::sleep_until(std::chrono::system_clock::now() + std::chrono::hours(std::numeric_limits<int>::max())); 

Or wait endlessly for a condition that will never be met.

 std::condition_variable cv; std::mutex m; std::unique_lock<std::mutex> lock(m); cv.wait(lock, []{return false;}); 

However, I see no reason for this.

+5
source

Instead of trying to figure out the time, why not sleep until the system’s maximum view time?

 std::this_thread::sleep_until(std::chrono::time_point<std::chrono::system_clock>::max()); 
+1
source

Another possibility:

 std::promise<void>().get_future().wait(); 

Or if you prefer:

 std::promise<void> p; p.get_future().wait(); 
+1
source

All Articles