【发布时间】:2013-06-27 02:24:24
【问题描述】:
我有一个循环,我想确保它在每个循环中运行(大约)固定的时间。
我正在使用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++(即不提升)来启用这种“等待”行为?
【问题讨论】:
-
我不知道,除非你使用
sleep_until。 -
这将是艰难的。如果你可以使用 boost,那么有很多定时回调函数可以让你轻松做到这一点。见here
-
我曾经在一个空的 fdset 上使用
select -
如果支持的话,你也可以试试内在的
yield。