5. Pragmatics

To compile with pthreads you must include the pthread header file, #include and must link to the pthread library. For example, cc hello_world.c -o hello_world -lpthreads (on the Alphas you should also include -lc_r). To use the semaphore library you must likewise include its header file and link to the object file or the library.

The DEC pthreads are based on the POSIX IV threads standard, not the POSIX VIII threads standard. The function pthread_join allows one thread to wait for another to exit. While this could be used in the hello world program to determine when the children are done instead of our decrement/up semaphore operations, the DEC implementation of pthread_join has unreliable behavior if the thread object specified no longer exists. For example, in the code below, if some_thread no longer exists, pthread_join may cause an error instead of just returning.

     pthread_t some_thread;
     void *exit_status;
     pthread_join( some_thread, &exit_status );
Other strange errors may occur from functions outside of the thread routines. While these errors are few and far between, some libraries make "uni-process" assumptions. For example, we have experienced intermittent difficulties with the buffered stream I/O functions fread and fwrite that can only be attributed to race conditions. On the issue of errors, though we did not check the return values of the thread calls in our examples to streamline them, the return values should be consistently checked. Almost all pthread related functions will return -1 on an error. For example:
     pthread_t some_thread;
     if ( pthread_create( &some_thread, ... ) == -1 )
          perror("Thread creation error");
The semaphore library will print a message and exit on erorrs. Some useful functions not covered in the examples:
pthread_yield();         Informs the scheduler that the thread is willing to yield its quantum, requires
                         no arguments.

pthread_t me;
me = pthread_self();     Allows a pthread to obtain its own identifier

pthread_t thread;
pthread_detach(thread);  Informs the library that the threads exit status will not be needed by
                         subsequent pthread_join calls resulting in better threads performance.
For more information consult the library or the man pages, e.g., man -k pthread..

Move to: Contents or Previous Section or Appendix A - Semaphore Code