HP aC++/HP C A.06.20 Programmer's Guide

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 wont 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);
}
216 Exception Handling