Multithreaded Programming Guide

Exit Print View

Updated: July 2014
 
 

Some Basic Guidelines for Threaded Code

  • Know what you are importing and know whether it is safe.

    A threaded program cannot arbitrarily enter nonthreaded code.

  • Threaded code can safely refer to unsafe code only from the initial thread.

    References to unsafe code in this way ensures that the static storage associated with the initial thread is used only by that thread.

  • When making a library safe for multithreaded use, do not thread global process operations.

    Do not change global operations, or actions with global side effects, to behave in a threaded manner. For example, if file I/O is changed to per-thread operation, threads cannot cooperate in accessing files.

    For thread-specific behavior, or thread cognizant behavior, use thread facilities. For example, when the termination of main() should terminate only the thread that is exiting main().

          pthread_exit();
           /*NOTREACHED*/
  • Oracle -supplied libraries are assumed to be unsafe unless explicitly documented as safe.

    If a reference manual entry does not explicitly state that an interface is MT-Safe, you should assume that the interface is unsafe.

  • Use compilation flags to manage binary incompatible source changes. See Chapter 8, Compiling and Debugging for complete instructions.

    • –mt enables multithreading.

    • –lpthreads used with the –mt option links in the POSIX threads functions. This flag is needed only if your program uses pthreads functions.

    • When using –mt, the Oracle Solaris threads APIs will be linked automatically. Always use the –mt option instead of listing –lthread explicitly. The libpthread library provides an interface to libthread, so you still need libthread when using pthreads.