睡一个加速螺纹几纳秒

时间:2011-07-09 18:39:46

标签: c++ multithreading boost sleep

我想要一个提升线程睡眠一段纳秒。以下代码是一个无错误编译的示例。但是,它没有按预期工作,我无法弄清楚原因。

#include <iostream>  
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time.hpp>
//Building options:
//-DBOOST_DATE_TIME_POSIX_TIME_STD_CONFIG -lboost_date_time-mt -lboost_thread-mt 
void replay()  
{
    boost::posix_time::time_duration time1, time2; 

    time1=boost::posix_time::seconds(3);
    std::cout << boost::posix_time::to_simple_string(time1) << std::endl;
    boost::this_thread::sleep(time1);

    time2=boost::posix_time::nanoseconds(987654321);
    std::cout << boost::posix_time::to_simple_string(time2) << std::endl;
    boost::this_thread::sleep(time2); 
}
int main(int argc, char* argv[])  
{  
    boost::thread replaythread(replay);  
    replaythread.join();
    return 0;  
}

BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG是为了使用纳秒(more info)所需的预处理器定义。当我设置-DBOOST_DATE_TIME_POSIX_TIME_STD_CONFIG构建选项时出现问题,然后boost :: this_thread :: sleep对任何posix :: time_duration都不起作用。创建的线程使用所有CPU,它不会休眠或处理剩余的指令。如果删除预处理器定义,则线程可以在任何时间段内休眠,除非boost :: posix_time :: nanoseconds。 该程序使用一些time_duration变量来存储纳秒,这使得boost :: this_thread :: sleep不起作用。

非常感谢你的时间

2 个答案:

答案 0 :(得分:7)

BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG会更改ptime的大小。

boost::this_thread::sleep是一个已编译的函数,在没有该定义的情况下编译(在您的发行版上),因此它需要微秒精度的ptime参数。你传递的是纳秒精度的ptime参数,函数失败了。

如果从boost库中提取代码并在启用此定义的情况下编译它,程序将按预期工作:

#include <iostream>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time.hpp>

// the guts of boost_1_46_1/libs/pthread/thread.cpp's version of sleep()
boost::mutex sleep_mutex;
boost::condition_variable sleep_condition;
void mysleep(const boost::posix_time::time_duration& dur)
{
    boost::system_time st = boost::get_system_time() + dur;
    boost::unique_lock<boost::mutex> lk(sleep_mutex);
    while(sleep_condition.timed_wait(lk, st));
}

void replay()
{
    boost::posix_time::time_duration time1, time2;

    time1=boost::posix_time::seconds(3);
    std::cout << boost::posix_time::to_simple_string(time1) << std::endl;
    mysleep(time1);
    //boost::this_thread::sleep(time1);

    time2=boost::posix_time::nanoseconds(987654321);
    std::cout << boost::posix_time::to_simple_string(time2) << std::endl;
    mysleep(time2);
    //boost::this_thread::sleep(time2);
}
int main()
{
    boost::thread replaythread(replay);
    replaythread.join();
    return 0;
}

答案 1 :(得分:2)

一些睡眠函数在被中断时会提前返回,所以你必须检查函数的返回值并再次调用它,直到它们返回零。