c ++ 为什么我的日期解析不是线程安全的
c++ Why is my date parsing not threadsafe?
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;
}
此函数应采用日期和格式字符串并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;
}
但是:为什么?
我看到有人打电话给local_time。我不确定底层代码是调用本地时间还是localtime_r。如果它调用本地时间,则它不是线程安全的。我相信 localtime 在返回结果时使用静态变量。
相关文章:
- 如何将元素添加到数组的线程安全函数?
- C++中的线程安全删除
- 在std::thread中,joinable()然后join()线程安全吗
- 在c++队列中使用pop和visit实现线程安全
- 以线程安全的方式调用"QQuickPaintedItem::updateImage(const QImage&image)"(no QThread)
- 全局变量 多读取器 一个写入器多线程安全?
- 共享队列的线程安全
- boost::文件系统::recursive_directory_iterator多线程安全
- 以线程安全的方式转换 C/C++ 中时区名称字符串的时区偏移量
- 线程安全运算符<<
- 如何使缓存线程安全
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 提升精神 V2 Qi 语法线程安全吗?
- asio 链对象线程安全吗?
- 线程安全队列 c++
- 提供对不同类型的数据(建议、代码审查)的线程安全访问的类
- 如何以线程安全的方式更改目录?
- 线程安全的引用计数队列C++
- 析构函数和线程安全
- 适用于大型数组的无复制线程安全环形缓冲区