JMU
Thread Safety
in Pthreads


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Review
Definitions
Thread-Safety and Reentrancy
Common Reasons Functions Aren't Thread-Safe
Adding Thread-Safety - Protect the Function
Adding Thread-Safety - Protect Shared Variables
Adding Thread-Safety - Pass State Information
Adding Thread-Safety - Pass State Information (cont.)
int 
running_total(int x)
{
  static int total = 0;

  total += x;
  return total;
}
  
int 
running_total(int x, int total)
{
  total += x;
  return total;
}
  
Adding Thread-Safety - Caller Allocates/Caller Frees
Adding Thread-Safety - Caller Allocates/Caller Frees (cont.)
void
running_total(int x, int *total)
{
  total += x;
  return total;
}
  
Adding Thread-Safety - Lock-and-Copy Wrappers
Adding Thread-Safety - Lock-and-Copy Wrappers (cont.)
// The function that can't be changed
int 
*running_total(int x)
{
  static int total = 0;

  total += x;
  return &total;
}
  
// The wrapped, thread-safe version
static pthread_mutex_t  running_total_mutex = PTHREAD_MUTEX_INITIALIZER;

int 
*running_total_ts(int x, int *private)
{
  int  *shared;

  pthread_mutex_lock(&running_total_mutex);
  shared = running_total(x);
  memcopy(private, shared, sizeof(int));
  pthread_mutex_unlock(&running_total_mutex);

  return private;
}
  
Adding Thread-Safety - Thread-Specific Data