简体   繁体   English

替代std :: this_thread :: sleep_for()

[英]alternative to std::this_thread::sleep_for()

I have a loop and I want to ensure that it runs for an (approximately) fixed amount of time for each loop. 我有一个循环,我想确保它在每个循环中(大约)固定的时间运行。

I am using sleep_for to achieve this behavior but I also want the program to be able to compile on environments that do not include full support of the standard thread library. 我正在使用sleep_for来实现此行为,但我也希望该程序能够在不完全支持标准线程库的环境下进行编译。 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 is also very CPU-intensive as the program checks continually for the time condition rather than waiting until it is true. 尽管这使程序可以在不支持标准线程的环境中进行编译,但它也非常占用CPU资源,因为程序会不断检查时间条件,而不是等到它成立为止。

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? 我的问题是:在不完全支持线程的环境中,是否有一种资源占用较少的方法仅使用标准C ++(即不增强)来启用这种“等待”行为?

There are many time based functions, it very much depends on the Operating system you're using. 有许多基于时间的功能,这在很大程度上取决于您所使用的操作系统。

Microsoft API offers Sleep() (capital S) which gives you a millisecond sleep. Microsoft API提供了Sleep()(大写S),可为您提供毫秒级的睡眠。

Under Unix (POSIX) you have nanosleep(). 在Unix(POSIX)下,您具有nanosleep()。

I think that these two functions should get you running on most computers. 我认为这两个功能应该可以使您在大多数计算机上运行。

The implementation would be to use the same loop, but sleep a little inside the while() loop. 实现将使用相同的循环,但在while()循环中要多睡一会。 That will still be a pool like thing, but faster much less CPU intensive. 那将仍然是一个类似池的事情,但是 速度更快 ,CPU占用更少。

Also, as nm mentioned, select() has that capability. 同样,如nm所提到的,select()具有该功能。 Just a bit more convoluted to implement, but it is expected to return once the time elapsed. 实施起来有些复杂,但是随着时间的流逝,它有望返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM