【问题标题】:boost::thread_specific_ptr slows drastically relative to simple TlsGetValue and TlsSetValueboost::thread_specific_ptr 相对于简单的 TlsGetValue 和 TlsSetValue 显着减慢
【发布时间】:2014-04-22 12:26:11
【问题描述】:

我有一个名为 WCThreadSpecificPrivateData 的小类。 其实现:

class WCThreadSpecificPrivateData
{
public:
    WCThreadSpecificPrivateData();
    ~WCThreadSpecificPrivateData();

    void* GetData();
    void  SetData(void*);

protected:
    uint32_t m_DataKey;
};

WCThreadSpecificPrivateData::WCThreadSpecificPrivateData():m_DataKey(0)
{
    m_DataKey = ::TlsAlloc();
}

void* WCThreadSpecificPrivateData::GetData()
{
    void* retVal = 0;

    if (0 != m_DataKey)
        retVal = ::TlsGetValue(m_DataKey);
    return retVal;
}

void  WCThreadSpecificPrivateData::SetData(void* in_data)
{
    if (0 != m_DataKey)
        ::TlsSetValue(m_DataKey, in_data);
}

我用它来存储指向名为 TargetSpecificData 的线程特定结构的指针。 在某些时候,我决定使用 boost::thread_specific_ptr 来代替这个类。它对我有用,但是,我的性能急剧下降。一切都变得更慢了。

我检查了 boost 实现(适用于 Windows),发现它也是通过 TlsGetValue 和 TlsSetValue 调用实现的,所以我预计会有大致相同的行为。有人可以提出导致这种下降的原因吗?

【问题讨论】:

    标签: c++ windows boost


    【解决方案1】:

    我不能给你很多想法“是什么导致了这种下降”,主要是因为你没有展示你如何使用thread_specific_ptr

    另外,考虑只使用thread_local (c++11),因为大多数编译器现在“大致”支持它。 (有一些小的限制,主要是非平凡类型的静态初始化)。没有什么不能用 lambda-initializer 解决的:

    thread_local std::unique_ptr<my_thing> thing = 
             [] { return new std::unique_ptr<my_thing>(); }();
    

    更新 事实上,这可能是有原因的:如果您正在创建许多线程(并让它们运行到完成),则可能会有更多的破坏(boost::thread_specific_ptr 在退出时破坏包含的实体boost::thread)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-08
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2014-09-20
      相关资源
      最近更新 更多