std::this_thread::sleep_for()的替代方法

alternative to std::this_thread::sleep_for()

本文关键字:方法 for this thread sleep std      更新时间:2023-10-16

我有一个循环,我想确保它为每个循环运行(大约)固定的时间。

我使用sleep_for来实现这种行为,但我也希望该程序能够在不完全支持标准线程库的环境中编译。现在我有这样的东西:

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
}

虽然这允许程序在不支持标准线程的环境中编译,但它也非常占用CPU,因为程序会不断检查时间条件,而不是等到它为真。

我的问题是:在不完全支持线程的环境中,是否有一种资源密集度较低的方法可以仅使用标准C++(即不使用boost)来启用这种"等待"行为?

有许多基于时间的函数,这在很大程度上取决于您使用的操作系统。

Microsoft API提供Sleep()(大写S),可让您获得毫秒级睡眠。

在Unix(POSIX)下,您可以使用nanosleep()。

我认为这两个功能应该能让你在大多数电脑上运行。

实现将使用相同的循环,但在while()循环中稍微休眠一点。这仍然是一个类似于池的东西,但更快的CPU密集度要低得多。

此外,正如n.m所提到的,select()具有这种功能。只是实现起来有点复杂,但预计它会在一段时间后返回。