提升线程无法正常睡眠,我错过了什么?

时间:2012-06-13 07:44:21

标签: boost real-time boost-thread thread-sleep

考虑以下示例,在Windows 7 icore7笔记本电脑(VC ++ 2010)和ubuntu 64bit 12.04 lte gcc 4.6.3

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp>
typedef boost::posix_time::ptime Time;
typedef boost::posix_time::time_duration TimeDuration;
int main()
{
    Time t1;
    Time t2;
    TimeDuration dt;
    boost::posix_time::microseconds tosleep=boost::posix_time::microseconds(100);
    for(int i=0;i<10;i++){

        t1=boost::posix_time::microsec_clock::local_time();
        //std::cout <<i << std::endl; // on win7 without this all outputs are 0
        boost::this_thread::sleep( tosleep );

        t2=boost::posix_time::microsec_clock::local_time();

        dt = t2 - t1;
        long long msec = dt.total_microseconds();
        std::cout << msec << std::endl;
    }
    return 0;
}

我期待我的线程会持续100微秒的睡眠,但输出很奇怪:

=========== AND OUTPUT ==================
arm2arm@cudastartub:~$ g++ -O3 sleepme.cpp -lboost_thread
arm2arm@cudastartub:~$ ./a.out
726
346
312
311
513
327
394
311
306
445

提升有一些开销吗?我需要什么样的实时系统,微秒是重要的?

1 个答案:

答案 0 :(得分:0)

在Windows上,不能睡眠()小于1毫秒,因此您的睡眠(睡眠)呼叫等同于睡眠(0)。 (另见this link

当然,std::cout <<i << std::endl需要一些时间......