我有一个 X 类:
class X { ... }
我想这样做:
void f()
{
thread_local static X x = ...;
...
}
(实际上我使用的是 gcc,所以关键字是“__thread”)
但我不能,因为你只能有微不足道的 thread_locals。
最好的解决方法是什么?
如果我这样做:
void f()
{
thread_local static X* p = 0;
if (!p)
p = new X(...);
X& x = *p;
...
}
然后:
- 线程退出时不会调用析构函数
- 不必要的动态内存分配。
更新:
这是我目前所拥有的:
#include <iostream>
#include <type_traits>
using namespace std;
class X { public: X() { cout << "X::X()" << endl; }; ~X() { cout << "X::~X()" << endl; } };
void f()
{
static __thread bool x_allocated = false;
static __thread aligned_storage<sizeof(X),
alignment_of<X>::value>::type x_storage;
if (!x_allocated)
{
new (&x_storage) X;
x_allocated = true;
// add thread cleanup that calls destructor
}
X& x = *((X*) &x_storage);
}
int main()
{
f();
}
这解决了动态内存分配问题。我只需要添加线程清理处理程序。有没有一种机制可以用 pthreads 来做到这一点?
最佳答案
标准描述了thread_local
作为存储说明符,与 §7.1.1 中的其他说明符( static
、 extern
等)一样。该词的任何定义都没有对“简单”数据类型的限制。
该问题在 pre-C++11 discussion document N2147 中进行了简要讨论。 (参见“线程变量动态初始化”部分)。其中包括对正确实现中涉及的关键问题的描述。显然 GCC 实现 ( static __thread
) 还没有解决这些问题(这与 GCC 不正式支持 C++11 thread_local
的事实一致)。
另一种选择是 boost::thread_specfic_ptr<>
提到in this earlier post并描述了here .
另一种选择是使用 std::thread
对象来实现线程并确保每个实例维护自己的变量拷贝,可能包含在 unique_ptr
中.
关于C++11:非平凡的线程局部静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12049095/