tau*_*ran 26 c++ boost thread-safety date-parsing gcc4
boost::posix_time::ptime parseDate(const std::string& format, const std::string& localDate)
{
std::istringstream is(localDate);
is.imbue(std::locale(is.getloc(), new boost::local_time::local_time_input_facet(format.c_str())));
boost::posix_time::ptime pt;
is >> pt;
if (pt == boost::posix_time::ptime())
{
throw std::runtime_error("Parse error");
}
return pt;
}
Run Code Online (Sandbox Code Playgroud)
此函数应采用日期和格式字符串和return boost::posix_time::ptime.
例如:2012:06:14 02:50:58和%Y:%m:%d %H:%M:%S.
但是,如果我在多线程程序中调用它,有时抛出异常,虽然format并且localDate是正确且可解析的(我对每次调用都使用相同的日期).我发现了一些关于std::stringstream/ std::locale线程问题但没有更新的东西(我正在使用gcc 4.6.3 64位).
这里有人有同样的问题:
使用Valgrind/drd测试过去几天,我发现我的代码中有很多部分会导致问题.例如,当调用一些提升日期时间转换函数时,我点击std :: locale(),这不是线程安全的.
更新的代码没有问题:
boost::posix_time::ptime parseDate(const std::string& format, const std::string& localDate)
{
std::istringstream is(localDate);
auto* facet = new boost::local_time::local_time_input_facet(format.c_str());
{
boost::unique_lock<boost::mutex> lock(globalLocaleMutex);
is.imbue(std::locale(is.getloc(), facet));
}
boost::posix_time::ptime pt;
is >> pt;
if (pt == boost::posix_time::ptime())
{
throw std::runtime_error("Parse error");
}
return pt;
}
Run Code Online (Sandbox Code Playgroud)
但仍然:为什么?
我看到有一个对 local_time 的调用。我不确定底层代码是否调用 localtime 还是 localtime_r。如果它调用 localtime,那么它就不是线程安全的。我相信 localtime 在返回结果时使用静态变量。
| 归档时间: |
|
| 查看次数: |
2283 次 |
| 最近记录: |