In C ++ 11, you can have a nontrivial object with thread_local storage:
class X { ... } void f() { thread_local X x = ...; ... }
Unfortunately, this function is not yet implemented in gcc (starting from 4.7).
gcc allows you to have local stream variables, but only with trivial types.
I am looking for a workaround:
Here is what I still have:
#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(); }
I need help calling placement_delete_x (& x_storage) when exiting the current thread. Is there a mechanism in pthreads and / or linux that I can use for this? Do I need to add a function pointer and parameter to some pthread cleanup stack?
Update:
I think pthread_cleanup_push might be what I want:
http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_cleanup_push.3.html
Will the cleanup handler call in the right circumstances for this use?
Update 2:
It looks like boost::thread_specific_ptr eventually calls pthread_key_create with the destructor parameter, not pthread_cleanup_push - to call the tls cleanup function:
http://pubs.opengroup.org/onlinepubs/009696799/functions/pthread_key_create.html
It is not clear what the difference is between the two methods, if any.
c ++ multithreading linux pthreads c ++ 11
Andrew Tomazos Aug 21 2018-12-12T00: 00Z
source share