c ++为什么我的日期解析不线程安全? [英] c++ Why is my date parsing not threadsafe?

查看:139
本文介绍了c ++为什么我的日期解析不线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This function should take a date and a format string and return boost::posix_time::ptime.

例如: 2012:06:14 02:50:58 %Y:%m:%d%H:%M:%S

然而,如果我在多线程程序中调用它,有时候抛出异常,虽然 format localDate 正确和可分析(我使用相同的日期为每个调用)。
我发现了 std :: stringstream / std :: locale 线程问题, -date(我使用gcc 4.6.3 64bit)。

However if I call it in a multithreaded program, sometimes the exception is thrown, although format and localDate are correct and parseable (I use the same date for every call). I found something about std::stringstream/std::locale thread issues but nothing up-to-date (I am using gcc 4.6.3 64bit).

这里有人有同样的问题:


过去几天使用Valgrind / drd测试我的代码的许多部分导致问题。例如,当调用一些boost日期时间转换函数时,我命中std :: locale(),这不是线程安全的。

Testing over the last few days using Valgrind/drd, I have found many parts of my code that cause problems. For example, when calling some boost date time conversion functions, I hit std::locale(), which is not threadsafe.

无问题的更新代码:

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或localtime_r。如果它调用localtime,那么它不是线程安全的。我相信localtime在返回结果时使用一个静态变量。

I see there is a call to local_time. I am not sure if the underlying code calls localtime or localtime_r. If it calls localtime, then it is not thread safe. I believe that localtime uses a static variable when it returns the result.

这篇关于c ++为什么我的日期解析不线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆