Posix threads

The Portable Operating System Interface (POSIX) defines an Application Programming Interface (API) for thread programming. Implementations of this interface exist for a large number of UNIX-like operating systems (GNU/Linux, Solaris, FreeBSD, OpenBSD, NetBSD, OS X), as well as for Microsoft Windows and others. Libraries that implement this standard (and functions of this standard) are usually called Pthreads.

To enable the creation of portable multi-threaded programs, the IEEE has defined the IEEE standard 1003.1c. Today an extended version of the standard is used - POSIX 1003.1-2001. The creation and control of threads are achieved by calling the POSIX Threads API.

The software model of pthreads defines:

  • Thread execution management (creating, joining threads etc.);
  • Managing shared process resources.

Pthreads defines a set of types and functions in the C programming language. The header file is pthread.h. Basic functions of the POSIX Threads API:

  • Types of data:
    • pthread_t - thread ID;
    • pthread_attr_t - list of thread attributes.
  • Functions for control:
    • pthread_create() - create a new thread;
    • pthread_exit() - terminate calling thread;
    • pthread_cancel() - send a cancellation request to a thread;
    • pthread_join() connect to another thread and wait for its termination;
    • pthread_detach() - disconnect from the thread;
    • pthread_attr_init() - initialize the thread attributes;
    • pthread_attr_setdetachstate, pthread_attr_getdetachstate - set/get detach state attribute in thread attributes object.
  • Functions for thread synchronization:
    • pthread_mutex_init(), pthread_mutex_destroy(), pthread_mutex_lock(), pthread_mutex_trylock();
    • pthread_cond_init(), pthread_cond_signal(), pthread_cond_wait().

An example illustrating the use of pthreads in C:

#include <pthread.h>
#include <stdio.h>

int count; /* shared data */
int atoi(const char *nptr);
void* perform(void *param); /* thread function */

int main(int argc, char *argv[])
{
  pthread_t tid; /* thread ID */
  pthread_attr_t attr; /* thread attributes */

if (argc != 2) {
  fprintf(stderr,"usage: progtest <integer value>\n");
  return -1;
}

if (atoi(argv[1]) < 0) {
  fprintf(stderr,"The parameter %d is not positive\n",atoi(argv[1]));
  return -1;
}

/* get attribute defaults */
  pthread_attr_init(&attr);

/* create a thread */
  pthread_create(&tid,&attr,perform,argv[1]);

/* wait for the thread to finish */
  pthread_join(tid,NULL);
  printf("count = %d\n",count);
}

/* thread function */
void* perform(void *param) 
{
  int i, upper = atoi(param);
  count = 0;

  if (upper > 0) {
    for (i = 1; i <= upper; i++)
    count += i;
  }

  pthread_exit(0);
}
Related program(s): CalculiX solver
Related report(s):