|
Ensuring the Mutual Exclusion of Shared Variables
in Pthreads |
|
Prof. David Bernstein
|
| Computer Science Department |
| bernstdh@jmu.edu |
thread_a probably finishes before
thread_b starts so the expected and actual
are the same
thread_a can read global_counter,
assign its value to local_counter, modify
local_counter, and then get swapped-off
before it writes global_counter
thread_b can then read global_counter
(which contains an incorrect value)
++global_counter
is not atomic meaning the same race condition exists
pthread_mutex_t variablespthread_mutex_t
variable becomes the "owner" of that variablepthread_mutex_t
variable can "unlock" (a.k.a. "release") itpthread_mutex_t will block until it
is "unlocked"pthread_mutex_t Variables)
static pthread_mutex_t example = PTHREAD_MUTEX_INITIALIZER
PTHREAD_MUTEX_ERROR_CHECK or
PTHREAD_MUTEX_RECURSIVE, neither
of which is the default)
EINVAL
EPERM
pthread_mutex_trylock() on the others. If
there are any errors release all of the locks, delay a random
amount of time, and try again.
PTHREAD_MUTEX_NORMAL
does not detect self-deadlock,
PTHREAD_MUTEX_ERRORCHECK provides error
checking, and PTHREAD_MUTEX_RECURSIVE
uses a lock count