Thread Safety
in Pthreads |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
malloc()
in C)
static
variable (e.g., a random number generator)static
Local Variable:
asctime()
returns a pointer to
a statically allocated date-time stringpthread_mutex_lock()
, and
the last statement is a call to
pthread_mutex_unlock()
int running_total(int x) { static int total = 0; total += x; return total; }
int running_total(int x, int total) { total += x; return total; }
void running_total(int x, int *total) { total += x; return total; }
// 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; }