睡一个加速螺纹几纳秒

Eme*_*mer 6 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;  
}
Run Code Online (Sandbox Code Playgroud)

BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG是为了使用纳秒(更多信息)所需的预处理器定义.当我设置-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不起作用.

非常感谢您的宝贵时间

Cub*_*bbi 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;
}
Run Code Online (Sandbox Code Playgroud)