HPC Pthreads Exercise: Hands-On Lab


Part I: The Fork-Join Pattern in Pthreads

The Portable Operating System Interface (POSIX) standard provides a library, commonly known as pthreads, which can be used for multithreading in C/C++ on any POSIX-compliant operating system. The pthreads library thus makes it possible to write portable multithreaded programs.

Unlike some libraries, pthreads is an explicit multithreading library, meaning the programmer must explicitly manage all threads. To use parallel patterns, we must therefore implement most of those patterns ourselves.

The Fork-Join pattern plays a central role in pthreads -- pretty much every pthreads program will use it. To let you explore it, here are some example pthreads programs, the first six of which you may use to explore various aspects of this pattern, including:

Each example includes a Makefile to simplify building it, so create a separate folder for each program and its Makefile.

Once you have explored these examples and are confident you understand how the Fork-Join pattern can be used in pthreads, you may continue to the next part of today's exercise.

Part II: The Mutual Exclusion Pattern in Pthreads

The Mutual Exclusion pattern is used to avoid race conditions when different threads need to access the same (shared) memory location. While multiple threads can simultaneously read from the same memory location without conflicting, any thread that tries to write to a memory location while another thread is reading or writing causes a conflict. In particular:

Such conflicts tend to produce non-deterministic behavior, which is usually a Bad Thing.

Sections of code where these conflicts occur are called critical sections. The Mutual Exclusion pattern is to prevent two threads from entering the critical section at the same time. The basic idea is to declare a shared variable that acts as a lock, and surround the critical section with calls to lock and unlock the lock:

   ...
   declare a "lock variable" shared by the threads 
   ...
   lock the "lock variable"

      critical section

   unlock the "lock variable"
   ...
With this pattern, before the first thread to reach the critical section can enter, it must first lock the lock. Until that thread leaves the critical section and unlocks the lock, any other threads that try to enter the critical section will find that the lock is locked and be forced to wait.

To support the Mutual Exclusion pattern, the pthread library provides:

The second part of today's exercise is to download and explore. this bank account simulation The simulation contains a race condition that you must fix using the Mutual Exclusion pattern.

When you have fixed the race condition, you may continue to this week's project.


CS > 374 > Exercise > 06 > Hands-On Lab


This page maintained by Joel Adams.