模拟线程局部变量
Simulate thread local variables
我想模拟非静态成员的线程局部变量,如下所示:
template< typename T, unsigned int tNumThread >
class ThreadLocal
{
private:
protected:
T mData[tNumThread];
unsigned int _getThreadIndex()
{
return ...; // i have a threadpool and each thread has an index from 0 to n
}
public:
ThreadLocal() {};
~ThreadLocal() {};
T& operator ->()
{
return mData[_getThreadIndex()];
}
...
};
但问题是线程数将在运行时确定,我必须从堆中分配mData
。
我想知道有没有办法不使用堆分配并使用上面的常规数组?
每个线程都有自己的堆栈,请记住,当函数返回时,堆栈帧会被弹出(或者可以被认为是弹出)。
这就是为什么我们有"无栈python",因为1个堆栈(python需要)和多个线程不能很好地发挥作用(参见全局解释器锁)
你可以把它放在main中,这将持续下去,但请记住C(++)想知道编译时的所有大小,所以如果线程计数发生变化(在编译时不固定),则无法知道这一点。
你真正想要的不是main的东西,但这不会是一个模板(在数字中),因为在编译时无法知道这个数字。
GCC 提供了一个堆栈分配函数(如 malloc),但我找不到它,最好避免使用它,因为这样优化实际上有效。
同样,不要低估 CPU 的预读能力和 GCC 优化,将阵列放在堆上也不错。
有趣的阅读与良好的图片,但不幸的是只与主题遥远相关:http://www.nongnu.org/avr-libc/user-manual/malloc.html
我建议:
std::unordered_map<std::thread::id, T, stackalloc> myTLS;
要么锁定所有访问权限,要么提前准备人口并在以后只读访问它。
您可以将其与堆栈分配器结合使用。
typedef short_alloc<pair<const thread::id, T>, maxthrds> stackalloc;
https://howardhinnant.github.io/stack_alloc.html
如果你想要另一个解决方案,在这里你可以做:
struct Padder
{
T t;
char space_[128 - sizeof(T)]; // if sizeof(T) >= 128 just don't include the padding.
};
std::array<Padder, maxthreads> myTLS;
实现 MESI 无瓶颈访问。
你必须关心使用此方法跟踪具有此数组中自己的索引的线程。
相关文章:
- 线程局部变量的初始化顺序
- C++:用IIFE线程初始化静态局部变量安全吗
- 在 OpenMP 中重置线程局部变量
- 是局部unordered_map变量线程在C 中安全的线程
- 线程局部变量的初始化
- 如果两个线程调用同一个函数,但函数中的所有变量都是局部变量,我还需要担心线程之间共享数据吗?
- 是包含线程局部变量重入的函数
- 为什么静态局部变量的 MSVC 线程安全初始化使用 TLS
- 我们是否需要原子地递增线程局部变量
- 如何使类静态变量线程安全
- 使用局部静态std :: ARNE_FLAG和局部静态指针对静态变量的线程安全初始化
- C 11-当我将局部变量作为参数传递到线程中时,它是否安全
- 使用局部全局变量在单独的线程中运行C函数
- C 11:STD Ref Global变量和非功能 - 局部线程界初始化订单
- 如何在c++中初始化线程局部变量
- 线程安全局部变量
- 命名空间中的全局变量 - 线程中的值不同
- 静态变量与堆栈变量:线程安全与堆栈大小
- 共享提升::shared_ptr<>变量线程安全吗?
- 在析构函数中pthead_join()类成员变量线程是否明智?