Mode-1 Multi-Core Memory Allocators OpenMP Intel TBB Pthreads Java - Threads Charm++ Prog. Message Passing (MPI) MPI - OpenMP MPI - Intel TBB MPI - Pthreads Compiler Opt. Features Threads-Perf. Math.Lib. Threads-Prof. & Tools Threads-I/O Perf. PGAS : UPC / CAF / GA Power-Perf. Home




Programming on Multi-Core Processors Using Pthreads (POSIX Threads)

Pthreads are defined as a set of C-language programming types and procedure calls, implemented with a pthread.h header/include file and a thread library. Solaris threads are easily understood by someone familiar with POSIX threads, and while Java threads and the multi-threading in the Win32 and OS/2 APIs are a little different . The subroutines, which comprise the Pthreads APIs, can be formally grouped into three classes such as Thread Management, Mutex Variables and Condition Variables. Threaded applications offer potential performance gains and practical advantages over non-threaded applications in several other ways as we can observe from the different programs.

Example programs using different APIs. Compilation and execution of Pthread programs, programs numerical and non-numerical computations are discussed using different thread APIs to understand Performance issues on mutli-core processors.

Example 1.1
Write a Pthread program to print Hello World .
Example 1.2
Write a Pthread program to find Sum of first n Natural Numbers.
Example 1.3
Write a Pthread program to illustrate pthread join operation.
Example 1.4
Write a Pthread program to illustrate basic stack management.
Example 1.5
Write a Pthread program to illustrate basic mutex operation.
Example 1.6
Write a Pthread program to explain condition variables.
Example 1.7
Write a Pthread program to find the minimum of an array.

(Source - References : Books     Multi-threading -[MCMTh-01], [MCMTh-02], [MCMTh-I03], [MCMTh-05], [MCMth-09], [MCMth-11], [MCMTh-15], [MCMTh-21], [MCBW-44] )

Description of Pthread Programs

Example 1.1 : Write a Pthread program to print "Hello World" using pthread_join Lib. Call
( Download source code : pthread-helloworld.c )


  • Objective
  • Write a Pthread program to print "Hello World" using pthread_join Lib. Call

  • Description
  • This is a very simple program to get the feel of threads and to get a view of how threads actually work. The implementation is as follows: The main thread creates two child threads. These threads print the words "Hello" and "World!" individually. Though there is no actual parallelism involved, this is just to demonstrate the working of threads. It is to be however noted that depending on the system load and the implementation of Pthreads Standard, the message may not always be "Hello World!". It can be "World! Hello" depending on which thread is scheduled to execute first. This also demonstrates the use of "Pthread_join".

  • Input
  • None

  • Output
  • Hello World! or World! Hello

Example 1.2 : Write a Pthread program to compute sum of first n natural numbers
( Download source code : pthread-sumn.c )


  • Objective
  • Write a Pthread program to print sum of first n natural numbers, based on mutual Exclusion

  • Description
  • This program prints the sum of first n natural numbers. This introduces the concept of a Mutex or a "Mutual Exclusion". Each thread adds its assigned number to a global variable. When all the threads are done, the global variable will contain the result. It uses a mutex variable to make sure that only one thread is updating the variable at any given time.

  • Input
  • Number of threads

  • Output
  • The sum of n natural numbers & the number of threads used

Example 1.3 : Write a program to illustrate thread-join operation.
( Download source code : pthread-join.c )


  • Objective
  • Write a program to illustrate thread-join operation.

  • Description
  • This example demonstrates how to "wait" for thread completions by using the Pthread join routine. Since some implementations of Pthreads may not create threads in a joinable state, the threads in this example are explicitly created in a joinable state so that they can be joined later.

  • Input
  • None

  • Output
  • The number of threads used

Example 1.4 : Write a Pthread program to illustrate basic stack management.
( Download source code : pthread-stack.c )


  • Objective
  • Write a Pthread program to illustrate basic stack management.

  • Description
  • pthread_attr_getstacksize(attr,stacksize);
    pthread_attr_getstacksize(attr,stacksize);

    The pthread_attr_getstacksize() and pthread_attr_setstacksize() functions, respectively, shall get and set the thread creation stacksize attribute in the attr object. The stacksize attribute shall define the minimum stack size (in bytes) allocated for the created threads stack.
    Upon successful completion, pthread_attr_getstacksize() and pthread_attr_setstack- size() shall return a value of 0; otherwise, an error number shall be returned to indicate the error.
    The pthread_attr_getstacksize() function stores the stacksize attribute value in stacksize if successful.

    pthread_attr_getstackaddr(attr,stackaddr);
    pthread_attr_setstackaddr(attr,stackaddr);
    The pthread_attr_getstackaddr() and pthread_attr_setstackaddr() functions, respectively, shall get and set the thread creation stackaddr attribute in the attr object.
    The stackaddr attribute specifies the location of storage to be used for the created thread's stack.
    Upon successful completion, pthread_attr_getstackaddr() and pthread_attr_setstack- addr() shall return a value of 0; otherwise, an error number shall be returned to indicate the error.
    The pthread_attr_getstackaddr() function stores the stackaddr attribute value in stackaddr if successful.

  • Input
  • None

  • Output
  • The number of threads used & print the stack size

Example 1.5 : Write a Pthread program to illustrate mutex operation.
( Download source code : pthread-mutex.c )


  • Objective
  • Write a Pthread program to illustrate mutex operation to computer dot product of vectors.

  • Description
  • This example program illustrates the use of mutex variables in a threads program that performs a dot product. The main data is made available to all threads through a globally accessible structure. Each thread works on a different part of the data. The main thread waits for all the threads to complete their computations, and then it prints the resulting sum.

    pthread_mutex_lock(mutex)
    The pthread_mutex_lock() routine is used by a thread to acquire a lock on the specified mutex variable. If the mutex is already locked by another thread, this call will block the calling thread until the mutex is unlocked.

    pthread_mutex_trylock(mutex)
    pthread_mutex_trylock() will attempt to lock a mutex. However, if the mutex is already locked, the routine will return immediately with a "busy" error code. This routine may be useful in preventing deadlock conditions, as in a priority-inversion situation.

    pthread_mutex_unlock(mutex)

    pthread_mutex_unlock() will unlock a mutex if called by the owning thread. Calling this routine is required after a thread has completed its use of protected data if other threads are to acquire the mutex for their work with the protected data. An error will be returned if:

    If the mutex was already unlocked
    If the mutex is owned by another thread

  • Input
  • Two input vector arrays of equal dimension

  • Output
  • The number of threads used & print the dot product of the vectors.

Example 1.6 : Write a Pthread program to illustrate condition variables.
( Download source code : pthread-conditionvariable.c )


  • Objective
  • Write a Pthread program to illustrate condition variable

  • Description
  • This simple example code demonstrates the use of several Pthread condition variable routines. The main routine creates three threads. Two of the threads perform work and update a "count" variable. The third thread waits until the count variable reaches a specified value.
    pthread_cond_init (condition,attr)
    pthread_cond_destroy (condition)
    pthread_condattr_init (attr)
    pthread_condattr_destroy (attr)


    Condition variables must be declared with type pthread_cond_t, and must be initialized before they can be used. There are two ways to initialize a condition variable:

  • Statically, when it is declared. For example: pthread_cond_t myconvar = PTHREAD_COND_INITIALIZER;

  • Dynamically, with the pthread_cond_init() routine,the ID of the created condition variable is returned to the calling thread through the condition parameter. This method permits setting condition variable object attributes attr.


  • The optional attr object is used to set condition variable attributes. There is only one attribute defined for condition variables: process-shared, which allows the condition variable to be seen by threads in other processes. The attribute object, if used, must be of type pthread_condattr_t (may be specified as NULL to accept defaults).

    Note that not all implementations may provide the process-shared attribute.

    The pthread_condattr_init() and pthread_condattr_destroy() routines are used to create and destroy condition variable attribute objects.

    pthread_cond_destroy() should be used to free a condition variable that is no longer needed.

    pthread_cond_wait (condition,mutex)
    pthread_cond_signal (condition)
    pthread_cond_broadcast (condition)


    pthread_cond_wait() blocks the calling thread until the specified condition is signaled. This routine should be called while mutex is locked, and it will automatically release the mutex while it waits. After signal is received and thread is awakened, mutex will be automatically locked for use by the thread. The programmer is then responsible for unlocking mutex when the thread is finished with it.

    The pthread_cond_signal() routine is used to signal (or wake up) another thread which is waiting on the condition variable. It should be called after mutex is locked, and must unlock mutex in order for pthread_cond_wait() routine to complete.

    The pthread_cond_broadcast() routine should be used instead of pthread_cond_signal() if more than one thread is in a blocking wait state.

    It is a logical error to call pthread_cond_signal() before calling pthread_cond_wait()

  • Input
  • Two input vector arrays of equal dimension

  • Output
  • The number of threads used & print the dot product of the vectors.

Example 1.7 : Write a Pthread program to find minimum of an array.
( Download source code : pthread_findmin.c )


  • Objective
  • Write a Pthread program to find minimum of an array

  • Description
  • This simple example code demonstrates the use of several Pthread mutex objects routines. It finds minimum of an array.

  • Input
  • Number of threads (Max of 8)

  • Output
  • Timetaken , minimum value

Centre for Development of Advanced Computing