C++11 では、thread_local ストレージを持つ自明でないオブジェクトを持つことができます。
class X { ... }
void f()
{
thread_local X x = ...;
...
}
残念ながら、この機能はまだ gcc に実装されていません (4.7 の時点)。
gcc では、スレッド ローカル変数を使用できますが、自明な型のみを使用できます。
回避策を探しています:
これが私がこれまでに持っているものです:
#include <iostream>
#include <type_traits>
using namespace std;
class X
{
public:
X() { cout << "X::X()" << endl; };
~X() { cout << "X::~X()" << endl; }
};
typedef aligned_storage<sizeof(X), alignment_of<X>::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
が欲しいものかもしれないと思います:
http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_cleanup_push.3.html
これは、この使用法に適した状況でクリーンアップ ハンドラーを呼び出しますか?
更新 2:
boost::thread_specific_ptr
最終的にはパラメーターを使用pthread_key_create
して呼び出すように見えますが、tls クリーンアップ関数を呼び出すには:destructor
pthread_cleanup_push
http://pubs.opengroup.org/onlinepubs/009696799/functions/pthread_key_create.html
これら 2 つの方法の違いがあるとしても、それが何であるかは不明です。?