std::this_thread::sleep_for()的替代方法
alternative to 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
}
虽然这允许程序在不支持标准线程的环境中编译,但它也非常占用CPU,因为程序会不断检查时间条件,而不是等到它为真。
我的问题是:在不完全支持线程的环境中,是否有一种资源密集度较低的方法可以仅使用标准C++(即不使用boost)来启用这种"等待"行为?
有许多基于时间的函数,这在很大程度上取决于您使用的操作系统。
Microsoft API提供Sleep()(大写S),可让您获得毫秒级睡眠。
在Unix(POSIX)下,您可以使用nanosleep()。
我认为这两个功能应该能让你在大多数电脑上运行。
实现将使用相同的循环,但在while()循环中稍微休眠一点。这仍然是一个类似于池的东西,但更快的CPU密集度要低得多。
此外,正如n.m所提到的,select()具有这种功能。只是实现起来有点复杂,但预计它会在一段时间后返回。
相关文章:
- 类方法 - 数据结构中 For 循环的运行时错误
- 从列表/向量制作嵌套 for 循环的最佳方法是什么?
- 从基于迭代器的for循环转换后,如何在map::find()中调用方法
- 如果子类中没有构造函数方法,则错误"no matching function for call to 'LGame::LGame(String&)'"
- 是否可以在基于范围的 for 循环中使用模板化的开始/结束方法
- 将 uint16 转换为 WMI Variant for CreateSnapshot 方法
- 使用for循环制作位图的最简单和最有效的方法
- 在 OpenGL ES for Android 中运行时创建大型纹理的最有效方法
- C++ 结束此 8 位 for 循环的最佳方法是什么
- 执行三个嵌套for循环的最快方法是什么
- BFS 方法中的 TLE for SPOJ AKBAR
- 这是在C++中使用 for 循环的正确方法吗?
- undefined 方法 'split' for nil:nilClass
- 是否有更简单的方法来定义C 中的for循环中的条件
- 这是使用基于范围的 for 循环的合理方法吗?
- 删除for-range循环中项目的最快方法
- C++ 中基于范围的 for 循环的替代方法
- 有没有一种方法可以访问for循环块之外的变量
- 在 for 循环中将结构传递给 pthread 的正确方法
- 有条件地控制 for 循环方向的最佳方法是什么