HP aC++/HP C Programmer's Guide (B3901-90036; A.06.26; September 2011)
Limitations
When using STL containers as local objects, the destructor will not get called when
pthread_exit is called, which leads to a memory leak. Do not call pthread_exit
from C++. Instead you must throw or return back to the thread’s initial function. There
you can do a return instead of pthread_exit.
Pthread library has no knowledge of C++ stack unwinding. Calling pthread_exit for
will terminate the thread without doing proper C++ stack unwind. That is, destructors for
local objects will not be called. (This is analogous to calling exit for single threaded
program.)
This can be fixed by calling destructors explicitly right before calling pthread_exit.
Example:
#include <pthread.h>
#include <stdlib.h>
#include <exception>
extern "C" int printf(const char*...);
struct A {
A () { printf("ctor called\n"); }
~A () { printf("dtor called\n"); }
};
struct B {
B () { printf("B ctor called\n"); }
~B () { printf("B dtor called\n"); }
};
__thread A* pA; // thread specific data.
void thread_specific_destroy(A *p) {
delete p;
}
typedef void fp(void*);
void* foo(void*) {
pA = new A();
B ob;
pthread_cleanup_push(reinterpret_cast<fp*>(thread_specific_destroy),pA);
pthread_cleanup_pop(1);
ob.~B(); // potential problem when the thread is canceled.
pthread_exit(0);
return 0;
}
int main() {
//A oa; exit(0);
//dtor for oa won’t be called if line above is uncommented.
pthread_t thread_id;
for (int i = 0; i < 3; i++)
pthread_create(&thread_id, 0, &foo, 0);
pthread_join(thread_id, 0);
}
Pthreads (POSIX Threads) 207