私はクラス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();
}
これにより、動的メモリ割り当ての問題が修正されます。スレッドクリーンアップハンドラーを追加する必要があります。pthreadでこれを行うメカニズムはありますか?