替代std :: this_thread :: sleep_for()

trm*_*trm 6 c++ c++11

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

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

}
Run Code Online (Sandbox Code Playgroud)

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

我的问题是:在不完全支持线程的环境中,是否存在资源消耗较少的方法来仅使用标准C++(即不提升)来启用此"等待"行为?

Ale*_*lke 2

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

Microsoft API 提供了 Sleep()(大写 S),它可以让您进入毫秒睡眠状态。

在 Unix (POSIX) 下有 nanosleep()。

我认为这两个功能应该可以让您在大多数计算机上运行。

实现将使用相同的循环,但在 while() 循环内稍微休眠一下。这仍然是一个类似池的东西,但速度更快,CPU 密集程度更低。

另外,正如 nm 提到的, select() 具有该功能。只是实施起来有点复杂,但预计时间一过就会返回。