如何分配线程本地存储? [英] How to allocate thread local storage?
本文介绍了如何分配线程本地存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的函数中有一个变量是静态的,但是我想在每个线程的基础上是静态的。
I have a variable in my function that is static, but I would like it to be static on a per thread basis.
如何分配内存我的C ++类,每个线程都有自己的类实例的副本?
How can I allocate the memory for my C++ class such that each thread has its own copy of the class instance?
AnotherClass::threadSpecificAction()
{
// How to allocate this with thread local storage?
static MyClass *instance = new MyClass();
instance->doSomething();
}
这是在Linux上。我不使用C ++ 0x,这是gcc v3.4.6。
This is on Linux. I'm not using C++0x and this is gcc v3.4.6.
推荐答案
#include <boost/thread/tss.hpp>
static boost::thread_specific_ptr< MyClass> instance;
if( ! instance.get() ) {
// first time called by this thread
// construct test element to be used in all subsequent calls from this thread
instance.reset( new MyClass);
}
instance->doSomething();
这篇关于如何分配线程本地存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文