是否可以通过thread_local实现boost::thread_specific_ptr
Is it possible to implement boost::thread_specific_ptr via thread_local?
这个问题看起来可能很奇怪。我之所以这么做,是因为我们有一些代码需要在几个平台上构建,但有些平台不支持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
面临的问题,比如使用什么键来查找映射中的值。但是,如果您的目标是消除依赖关系,那么这种方法可能会很有用。
- 在std::thread中,joinable()然后join()线程安全吗
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 分离一个静态常量 std::thread?
- 尝试使用 std::vector<std::thread时出现静态断言失败错误>
- 使用 thread 类在 C++ 中构造线程的动态数组时出错
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 如何从 std::thread 返回值
- 在C++中使用并行化的预期速度是多少(不是 OpenMp,而是 <thread>)
- 为共享 ptr 向量实现复制 c'tor?
- 将 std::thread by 值推送到列表中
- 转发变量参数列表以模拟 std::thread
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 嵌入式设备 -> std::thread -> FreeRTOS?
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- std::thread 增加 DLL 引用计数,从而防止卸载 DLL
- 如何防止 std::thread 在 QT 中冻结 GUI?