Jump to content United States-English
HP.com Home Products and Services Support and Drivers Solutions How to Buy
» Contact HP
More options
HP.com home
HP Itanium-based Systems: HP aC++/HP C Programmer's Guide > Chapter 8 Exception Handling

Pthreads (POSIX Threads)

» 

Technical documentation

Complete book in PDF
» Feedback
Content starts here

 » Table of Contents

 » Glossary

 » Index

Pthreads (POSIX threads) refers to the Pthreads library of thread-management routines. For information on Pthread routines see the pthread(3t) man page. To use the Pthread routines, your program must include the <pthreads.h> header file and the Pthreads library must be explicitly linked to your program.

Example:

aCC -mt prog.c

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);
}
NOTE: vector::clear() does not free all of the memory. The storage is put back into a free pool for that one container.

This does not happen if a thread is canceled. In such cases, use thread specific data or thread local storage support along with pthread_cleanup_[push|pop] utilities.

pthread_cancel is not supported.

Printable version
Privacy statement Using this site means you accept its terms Feedback to webmaster
© Hewlett-Packard Development Company, L.P.