Pthreads is the POSIX standard (IEEE 1003.1c) defines an API for thread creation and synchronization. It is only a specification, not implementation which a programmer can do any way they wish.


Some examples of systems using are Solaris, Linux, Mac OS X, and True64 UNIX.

Here is an example of Pthread API for constructing a multi-threaded program that calculates “summation of a non-negative integer” in a separate thread.

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

int sum /* this data is shared by threads */
void *runner(void *param); /* the thread that do summation */

int main(int argc, char *argv[])

pthread_t tid; /* the thread identifier */
pthread_attr_t attr ; /* set of thread attributes */

if (argc != 2) {
fprintf(stderr, "usage: a.out <integer value>\n");
return -1;
if (atoi(argv[1]) < 0) { 
fprint(stderr, "%d must be >= 0\n",atoi(argv[1]));
return -1;

/* get the default attributes */


/* create the thread */

pthread_create(&tid,&attr, runner,argv[1]);

/* wait for the thread to exit */


printf("sum = %d\n",sum);

/* the thread will begin control in this function */

void *runner(void *param)
int i; upper = atoi(param);
sum = 0;

for (i = 1; i <= upper; i++)
sum+= i;


The main program has a Pthread header included. The variables Pthread_t and pthread_attr_t are thread identifier and attributes for the thread.

The pthread_attr_init(&attr) sets the default attributes for the thread.

pthread_create(&tid, &attr,runner, argv[1]);

The above will create a new thread which is the runner function. The main function is the main thread that creates the second thread runner. Both threads run in its own function. Once control return to the main thread, it prints the results and exit thread – pthread_exit();.


  • Abraham Silberschatz, Peter B. Galvin, Greg Gagne (July 29, 2008) Operating System Concepts, 8 edn., : Wiley.
  • Tanenbaum, Andrew S. (March 3, 2001) Modern Operating Systems, 2nd edn., : Prentice Hall.


Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.