P.X*_*P.X 6 c++ boost thread-local-storage c++11
这个问题可能看起来很奇怪。我想这样做是因为我们有一些代码需要在多个平台上构建,但有些平台不支持 thread_local,然后使用 boost::thread_specific_ptr 代替。然而,为每个平台(x86/x64/arm、调试/发布、操作系统,太多)构建 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
Run Code Online (Sandbox Code Playgroud)
我找不到路,也许你可以,谢谢。
可以thread_specific_ptr使用来实现thread_local。必须记住的重要部分是它thread_local是一个存储说明符并且thread_specific_ptr是一个对象。因此,从技术上讲,动态创建和销毁对象是可能的thread_specific_ptr,但不能用thread_local对象来做到这一点。例如,您不能将thread_local对象作为类的成员。
但是,thread_local可以在内部使用,thread_specific_ptr根据当前线程选择内部结构。thread_specific_ptr该结构可以包含程序中所有 s 的数据,并允许动态创建和删除其元素。std::map例如,可以使用 a来达到此目的。
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;
}
};
Run Code Online (Sandbox Code Playgroud)
当然,与 的原始使用相比,这会增加一些开销thread_local,并且实际上可能比boost::thread_specific_ptr在某些平台上慢一些,因为boost::thread_specific_ptr使用比thread_local. 您还必须解决boost::thread_specific_ptr面临的问题,例如使用什么键来查找地图中的值。但如果您的目标是消除依赖性,则此方法可能很有用。