First, the use of mutual exclusion locks
1, the initialization of mutual exclusion
The pthread_mutex_t mutex =pthread_mutex_initializer;//statically initializes the mutex
int pthread_mutex_init (Pthread_mutex_t*mutex, PTHREAD_MUTEXATTR_T*ATTR)//dynamic initialization Mutex
int pthread_mutex_destory (PTHREAD_MUTEX_T*MUTEX);/Undo Mutex
You cannot copy a mutex variable, but you can copy a pointer to a mutex so that multiple functions or threads can share the mutex to achieve synchronization. The mutex that is dynamically requested above requires a dynamic revocation.
2, lock and unlock mutually exclusive amount
int Pthread_mutex_lock (pthread_mutex_t *mutex);
int Pthread_mutex_trylock (pthread_mutex_t *mutex);
int Pthread_mutex_unlock (PTHREAD_MUTEX_T*MUTEX);
When a pthread_mutex_lock lock mutex is invoked, the calling thread is blocked if the mutex is already locked. The Pthread_mutex_trylock function returns an error code ebusy when the calling mutex is already locked. Using the same as the semaphore, lock the mutex before processing the shared data, and finally unlock the mutex.
Modified for the example on the upper semaphore:
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#define Niters 100000000
/* Shared variable *
/unsigned int cnt = 0;
Sem_t Mutex;
pthread_mutex_t Mutex;
void *count (void *arg)
{
int i;
for (i=0;i<niters;i++)
{
pthread_mutex_lock (&mutex);
cnt++;
Pthread_mutex_unlock (&mutex);
}
return arg;
}
int main ()
{
pthread_t tid1,tid2;
int status;
Pthread_mutex_init (&mutex,null);
Pthread_mutex_destroy (&mutex);
if (cnt!= (unsigned) niters*2)
printf ("boom!,cnt=%d\n", CNT);
else
printf ("OK cnt=%d\n", CNT);
return 0;
}
3. Using multiple mutexes
Using multiple mutexes can cause a deadlock problem. As follows:
Thread 1 thread 2
pthread_mutex_lock (&mutex_a); Pthread_mutex_lock (&mutex_b);
Pthread_mutex_lock (&mutex_b); Pthread_mutex_lock (&mutex_a);
When two threads complete the first step, the second step cannot be completed, resulting in a deadlock. There are two ways to avoid deadlocks:
Fixed lock level: All code that needs to lock both mutex A and mutex B at the same time, must lock A and lock B first.
Try lock and rollback: After locking the first mutex, use Pthread_mutex_trylock to lock the other mutex, and if it fails, releases the locked mutex and locks it again.
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/unix/