【发布时间】:2016-11-23 13:49:45
【问题描述】:
这是我正在研究的一个库的缩略:
class pool
{
private:
std::vector<int> m_buffer;
public:
void insert(int a) { m_buffer.push_back(a); }
int size() { return (int)(m_buffer.size()); }
virtual ~pool() {}
};
class customMem
{
public:
static thread_local pool poolmanager;
static boost::thread_specific_ptr< pool> poolmanager_boost;
};
thread_local pool customMem::poolmanager;
boost::thread_specific_ptr< pool > customMem::poolmanager_boost; //very slow
class MVeryLongData : public customMem
{
public:
MVeryLongData(bool localthread, int a)
{
if (localthread)
{
customMem::poolmanager.insert(a);
}
else
{
if (!customMem::poolmanager_boost.get()) {
// first time called by this thread
// construct test element to be used in all subsequent calls from this thread
customMem::poolmanager_boost.reset(new pool);
}
customMem::poolmanager_boost->insert(a);
}
}
int size() { return customMem::poolmanager.size(); }
};
void func(bool localthread)
{
#pragma omp parallel for
for (int i = 0; i < 10000000; i++)
{
MVeryLongData a(localthread, i);
}
}
我想知道是否有办法通过以某种方式合并 poolmanager_boost 和 poolmanager 来摆脱函数 func 中的 bool localthread。 调用这两个变量的原因是在 Visual Studio C++ 12 中不完全支持 thread_local。
如果可能,请告诉我(合并)。我可以使用标准条件吗?
请注意,我试图避免使用模板。
编辑:由于我找不到我的问题的解决方案,我想我别无选择,只能使用模板。所以使用模板的解决方案也值得赞赏。类似于 getter 函数,它返回一个 boost_thread_ptr 或 thread_local pool* 的指针。
【问题讨论】:
-
那你倒霉了。这就是模板的用途。唯一的其他解决方案是混乱的并且涉及宏。
-
我避免使用模板,因为 customMem 已用于许多其他位置。这意味着我想我也必须触摸它们。我说的对吗?
-
bool localthread是编译时间常数吗? -
@StoryTeller 是的。这将是编译时间常数。正如我在问题中提到的,双重声明的原因是编译器不同。
-
我不明白你想如何在 poolmanager 和 poolmanager_boost 之间进行选择,否则是否使用模板,两者似乎都可能,对于非模板解决方案,定义一个具有虚拟插入方法的接口,池管理器和poolmanager_boost(或它的后代)将继承应该做的伎俩
标签: c++ boost-thread