Using Threads

The HP aC++ run-time environment supports multi-threaded applications.

The following HP aC++ libraries are thread-safe:

In order to pick the thread safe version of I/O routines (cout, cin, cerr, and clog) when you include iostream.h in your source files, you can add the -D_THREAD_SAFE compile time flag to your compilation line.

To guarantee that your I/O results from one thread are not intermingled with I/O results from other threads, you must protect your I/O statement with locks. (Note, if you use locks, you do not have to use the -D_THREAD_SAFE compile time flag.) For example:

// create a mutex and initialize it pthread_mutex_t the_mutex; #ifdef _PTHREADS_DRAFT4 // for user threads pthread_mutex_init(&the_mutex, pthread_mutexattr_default); #else // for kernel threads pthread_mutex_init(&the_mutex, (pthread_mutexattr_t *)NULL); #endif pthread_mutex_lock(&the_mutex); cout << "something" ... ; pthread_mutex_unlock(&_the_mutex);

Note that conditional compilation may be necessary to accomodate both the user threads and the kernel threads interfaces, as in the above example.

Required Command-line Options

To use the multi-thread safe capabilities of the Standard C++ Library and the Tools.h++ Library, you need to specify the following options at both compile and link time:

WARNING: If you do not specify these options, a run-time error will be generated or multi-thread behavior will be incorrect.

For More Information

For information on using threads and writing multi-threaded applications: