Alternative std :: this_thread :: sleep_for ()

I have a loop, and I want to make sure that it works for a (approximately) fixed amount of time for each loop.

I use sleep_for to achieve this behavior, but I also want the program to compile in environments that do not include full support for the standard thread library. Right now I have something like this:

 using namespace std; using namespace std::chrono; // while( !quit ) { steady_clock::time_point then = steady_clock::now(); //...do loop stuff steady_clock::time_point now = steady_clock::now(); #ifdef NOTHREADS // version for systems without thread support while( duration_cast< microseconds >( now - then ).count() < 10000 ) { now = steady_clock::now(); } #else this_thread::sleep_for( microseconds{ 10000 - duration_cast<microseconds>( now - then ).count() } ); #endif } 

While this allows the program to compile in environments that do not support standard threads, it also requires a processor very intensively, because the program constantly checks the time condition, rather than waiting until it is true.

My question is: is there a less resource-intensive way to enable this β€œwait” behavior using only standard C ++ (ie not boost) in an environment that does not fully support threads?

+6
source share
1 answer

There are many functions based on time, it very much depends on the operating system that you use.

The Microsoft API offers Sleep () (capital S), which gives you a millisecond sleep.

On Unix (POSIX) you have nanosleep ().

I think that these two functions should run on most computers.

The implementation will be to use the same loop, but sleeping a bit inside the while () loop. It will still be a pool, like a thing, but much less CPU is faster .

In addition, as pm mentioned, select () has this capability. Just a little confusing to implement, but it is expected to return in time.

+2
source

Source: https://habr.com/ru/post/948179/


All Articles