C++提高睡眠准确性

buc*_*tak 3 c++ sleep boost-thread

我遇到了boost::sleep()功能上的奇怪问题.我有这个基本代码:

#include <sys/time.h>
#include <boost/chrono.hpp>
#include <boost/thread.hpp>

void thread_func()
{
    timeval start, end;
    gettimeofday( &start, NULL );
    boost::this_thread::sleep( boost::posix_time::milliseconds(1) ); // usleep(1000) here works just fine.
    gettimeofday( &end, NULL );

    int secs = end.tv_sec - start.tv_sec;
    int usec = end.tv_usec - start.tv_usec;
    std::cout << "Elapsed time: " << secs << " s and " << usec << " us" << std::endl;
}

int main()
{
    thread_func();

    boost::thread thread = boost::thread( thread_func );
    thread.join();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

问题是boost::sleep()函数在创建的线程和主线程中的行为不同.这个程序的输出是

Elapsed time: 0 s and 1066 us
Elapsed time: 0 s and 101083 us
Run Code Online (Sandbox Code Playgroud)

boost::sleep()函数在创建的线程中休眠100毫秒,而在主线程中它可以正常工作(它休眠1毫秒).如果我在创建的线程中,我无法获得低于100毫秒的精度(例如通过使用boost::posix_time::microseconds).但是,如果我使用usleep(1000)它,它的工作正常.

我在Intel i7 CPU上使用Fedora 18(64位)3.8.4和Boost 1.50.0-5.fc18.我还使用Win 7和Boost 1.48.0测试了不同PC上的代码并且没有出现问题,所以我猜它应该与系统配置有关,但我不知道如何.

Use*_*ess 5

boost::this_thread::sleep已弃用(请参阅文档).

usleep 也已弃用(在POSIX.1-2001中已过时,已从POSIX.1-2008中删除).

FWIW,在我本地安装的较旧(1.44)boost标题中,boost::this_thread_sleep实际调用的相对延迟版本gettimeofday计算绝对截止时间,然后转发到绝对版本(这是编译成行外的,所以我不把它放在手边).请注意,gettimeofday标志着POSIX.1-2008过时.

所有这些建议的替代品是:

  • boost::this_thread::sleep_for而不是...::sleep相对延迟
  • boost::this_thread::sleep_until而不是...::sleep绝对的时间
  • nanosleep 代替 usleep
  • clock_gettime 代替 gettimeofday