gpt4 book ai didi

c++ - 如何使用非平凡构造函数构造静态 thread_local 成员

转载 作者:行者123 更新时间:2023-11-30 04:50:21 26 4
gpt4 key购买 nike

我有一个我想构造的类成员,它应该是访问它的每个线程的本地成员。虽然构造函数需要一些参数,所以我不能依赖静态零初始化。

class ThreadMem{
public:
ThreadMem(uint32 cachelineSize, uint32 cachelineCount);
};

class ThreadPool{
public:
ThreadPool(uint32 cachelineSize, uint32 cachelineCount){
// I need to prepare the `m_mem` in other threads with these arguments somehow
}
ThreadMem & mem() {
return m_mem;
}
private:
static thread_local ThreadMem m_mem;
};

哪里是构建static thread_local ThreadMem ThreadPool::m_mem 的最佳位置,这样每个线程只构建一次,只有ThreadPool 的构建线程可以使用值在运行时计算?

最佳答案

该静态类成员由 C++ 运行时在进入 main 之前的动态初始化阶段构造。其构造函数的参数必须在那时可用,这可能是不可行的。

关于c++ - 如何使用非平凡构造函数构造静态 thread_local 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55008477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com