我试图找到一种线程安全的方式来获取当地时间。从boost示例中,我得到了这个:
#include "boost/date_time/posix_time/posix_time.hpp"
#include <iostream>
int
main()
{
using namespace boost::posix_time;
using namespace boost::gregorian;
//get the current time from the clock -- one second resolution
ptime now = second_clock::local_time();
//Get the date part out of the time
date today = now.date();
date tommorrow = today + days(1);
ptime tommorrow_start(tommorrow); //midnight
//iterator adds by one hour
time_iterator titr(now,hours(1));
for (; titr < tommorrow_start; ++titr) {
std::cout << to_simple_string(*titr) << std::endl;
}
time_duration remaining = tommorrow_start - now;
std::cout << "Time left till midnight: "
<< to_simple_string(remaining) << std::endl;
return 0;
}
但我不知道它是否可以在多线程环境中使用?
答案 0 :(得分:2)
是的,您的平台支持它:
在定义BOOST_HAS_THREADS时,日期时间现在在支持它们的平台上使用可重入的POSIX函数。
来自here
这些天基本上总是定义BOOST_HAS_THREADS。如果您有疑问,可以查看平台的POSIX支持。