c ++ 为什么我的日期解析不是线程安全的

c++ Why is my date parsing not threadsafe?

本文关键字:线程 安全 为什么 我的 日期      更新时间:2023-10-16
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

但是,如果我在多线程程序中调用它,有时会抛出异常,尽管formatlocalDate是正确的且可解析的(我每次调用都使用相同的日期)。我发现了一些关于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 在返回结果时使用静态变量。