C++ c++;为什么我的约会解析不是线程安全的?

C++ c++;为什么我的约会解析不是线程安全的?,c++,boost,thread-safety,gcc4,date-parsing,C++,Boost,Thread Safety,Gcc4,Date Parsing,此函数应采用日期和格式字符串,并返回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位) 有些人也有同样的问题: 在过去几天使用Valgr

此函数应采用日期和格式字符串,并
返回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进行的测试中,我发现我的代码中有许多部分会导致问题。例如,在调用一些boost日期-时间转换函数时,我点击了std::locale(),这不是线程安全的

更新的代码没有问题:

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;
}
boost::posix_time::ptime parseDate(const std::string&format,const std::string&localDate)
{
std::istringstream是(localDate);
auto*facet=newboost::local_time::local_time_input_facet(format.c_str());
{
boost::unique_lock锁(globalLocaleMutex);
is.imbue(std::locale(is.getloc(),facet));
}
boost::posix_time::ptime pt;
is>>pt;
if(pt==boost::posix_time::ptime())
{
抛出std::运行时_错误(“解析错误”);
}
返回pt;
}

但还是:为什么?

我看到有人打电话到当地时间。我不确定底层代码是调用localtime还是localtime\r。如果它调用localtime,则它不是线程安全的。我相信localtime在返回结果时使用静态变量。

您使用的是多线程运行库吗?例如,VisualStudio有两种类型——单线程和多线程。根据您的分析,您的问题是否真的是“为什么std::locale不是线程安全的?”是的!你的问题真的是为什么?我的问题是为什么?听起来像是libstdc++:std::locale构造函数中的一个bug,不需要任何锁定。我可以建议您向GCC报告错误报告吗?你有没有试过进入std::locale-ctor,看看那里做了哪些不安全的事情?
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;
}