在C 11中,您可以使用thread_local存储创建一个非平凡的对象:
class X { ... }
void f()
{
thread_local X x = ...;
...
}
不幸的是,这个功能还没有在gcc中实现(截至4.7).
gcc允许你拥有线程局部变量,但只允许使用普通类型.
我正在寻找一个解决方法:
这是我到目前为止:
#include
#include
using namespace std;
class X
{
public:
X() { cout << "X::X()" << endl; };
~X() { cout << "X::~X()" << endl; }
};
typedef aligned_storage::value>::type XStorage;
inline void placement_delete_x(X* p) { p->~X(); }
void f()
{
static __thread bool x_allocated = false;
static __thread XStorage x_storage;
if (!x_allocated)
{
new (&x_storage) X;
x_allocated = true;
// TODO: add thread cleanup that
// calls placement_delete_x(&x_storage)
}
X& x = *((X*) &x_storage);
}
int main()
{
f();
}
我需要帮助的是在退出当前线程时调用placement_delete_x(& x_storage).我可以使用pthreads和/或linux中的机制来做到这一点吗?我需要将函数指针和参数添加到某种pthread清理堆栈中吗?
更新:
我认为pthread_cleanup_push可能就是我想要的:
这会在正确的情况下调用清理处理程序吗?
更新2:
看起来boost :: thread_specific_ptr最终使用析构函数参数调用pthread_key_create,而不是pthread_cleanup_push – 调用它的tls清理函数:
目前还不清楚这两种方法之间的区别是什么,如果有的话. ?