I have a class X:
class X { ... }
I want to do this:
void f()
{
thread_local static X x = ...;
...
}
(actually I'm using gcc so keyword is "__thread")
but I can't because you can only have trivial thread_locals.
What is the best work-around for this?
If I do it this way:
void f()
{
thread_local static X* p = 0;
if (!p)
p = new X(...);
X& x = *p;
...
}
then:
- the destructor won't be called when thread exits
- unnecessary dynamic memory allocation.
Update:
Here is what I have so far:
#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();
}
This fixes the dynamic memory allocation problem. I just need to add the thread cleanup handler. Is there a mechanism to do this with pthreads?