是否可以通过thread_local实现boost::thread_specific_ptr

Is it possible to implement boost::thread_specific_ptr via thread_local?

本文关键字:thread ptr specific boost local 可以通过 是否 实现      更新时间:2023-10-16

这个问题看起来可能很奇怪。我之所以这么做,是因为我们有一些代码需要在几个平台上构建,但有些平台不支持thread_local,请改用boost::thread_specific_ptr。然而,为每个平台(x86/x64/arm、debug/release、os,太多)构建boost二进制文件是令人不快的。

我想知道是否可以通过thread_local导入thread_specific_ptr,这样我们就可以保持客户端代码更优雅(避免#ifdef)

我想要一个标题文件,如:

#if HAS_THREAD_LOCAL
class thread_specific_ptr
{
    ... // use thread_local to implement
};
#else
using boost::thread_specific_ptr
#endif

我找不到路,也许你可以,谢谢。

使用thread_local可以实现thread_specific_ptr。必须记住的重要部分是thread_local是存储说明符,thread_specific_ptr是对象。因此,在技术上可以动态创建和销毁thread_specific_ptr对象,而不能使用thread_local对象。例如,不能将thread_local对象作为类的成员。

但是,thread_specific_ptr可以在内部使用thread_local来选择基于当前线程的内部结构。该结构可以包含程序中所有thread_specific_ptr的数据,并允许动态创建和删除其元素。例如,可以为此目的使用std::map

thread_local std::map< void*, std::shared_ptr< void > > thread_specific_ptr_data;
template< typename T >
class thread_specific_ptr
{
public:
    T* get() const
    {
        auto it = thread_specific_ptr_data.find(this);
        if (it != thread_specific_ptr_data.end())
            return static_cast< T* >(it->second.get());
        return nullptr;
    }
};

当然,与thread_local的原始使用相比,这增加了一些开销,而且在某些平台上,它实际上可能比boost::thread_specific_ptr慢一点,因为boost::thread_specific_ptr使用的接口级别低于thread_local。您还必须解决boost::thread_specific_ptr面临的问题,比如使用什么键来查找映射中的值。但是,如果您的目标是消除依赖关系,那么这种方法可能会很有用。