小编trm*_*trm的帖子

替代std :: this_thread :: sleep_for()

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

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++(即不提升)来启用此"等待"行为?

c++ c++11

6
推荐指数
1
解决办法
1178
查看次数

标签 统计

c++ ×1

c++11 ×1