|
pthread_mutex_t x; |
After defining the mutex lock variable, you must initialized it using the following function:
int pthread_mutex_init(pthread_mutex_t *mutex, pthread_mutexattr_t *attr ); |
The most common mutex lock is one where the lock is initially in the unlock.
This kind of mutex lock is created using the (default) attribute null:
Example: initialize a mutex variable
pthread_mutex_t x; /* Define a mutex lock "x" */ pthread_mutex_init(&x, NULL); /* Initialize "x" */ |
int pthread_mutex_lock(pthread_mutex_t *mutex); |
Example:
pthread_mutex_t x; pthread_mutex_init(&x, NULL); ... pthread_mutex_lock(&x); |
int pthread_mutex_unlock(pthread_mutex_t *mutex); |
Example:
pthread_mutex_unlock(&x); |
Whenever a thread want to update a shared variable, it must enclose the operation between a "lock - unlock" pair.
Example:
int N; // SHARED variable pthread_mutex_t N_mutex; // Mutex controlling access to N void *worker(void *arg) { int i; for (i = 0; i < 10000; i = i + 1) { pthread_mutex_lock(&N_mutex); N = N + 1; pthread_mutex_unlock(&N_mutex); } } |
This particular thread will then be the only thread that will update the variable N, thus ensuring that N is updated sequential (one thread after another)
Compare the behavior of this program with the one that does not use MUTEX to control access to N: click here
A common error in parallel programs is to forget the unlock call (especially if the call is made after many statments)... the result is deadlock - you program hangs (no progress)