Threads often use the same memory space and data structures. This makes unsafe to allow simultaneous access to such resources or data without a protocol for safe access.

MUTEX or Mutual Exclusion is the method  used to check this and give a serializing access to shared resources & data. It is like lock which can be attached to any resource when used by a thread which blocks other threads to access it. Also, when one thread has managed to lock a mutex, another thread has to wait till the lock is removed to be able to lock it again.

Mutex types :

  • Recursive : This is used in recursive algorithms where a thread holding the lock is allowed to lock the again.
  • Queuing : FIFO (First In First Out) ordering of lock requests is followed.It is relatively slower.
  • Reader/Writer : This allows for more than one reader lock at the same time on any resource or data structure. When all readers unblock the lock then only writer is allowed to put a lock & use the resource.

Creating And Initializing a Mutex :

Variable declaration for Mutex is of type :    pthread_mutex_t  .  Mutexes can be initialized to default values through a macro rather than a function call like :

pthread_mutex_t lock_a = PTHREAD_MUTEX_INITIALIZER;

Here, a mutex object named lock_a is initialized to default pthread mutex values. This type of initialization creates a mutex called fast mutex. This means that if a thread locks the mutex and then tries to lock it again,  it will be in a deadlock.

Pthread mutexes can also be created through following function call :

int pthread_mutex_init(pthread_mutex_t *mutex, NULL)

This function requires the same above mentioned variable as first argument. Attributes can be given through second variables or for default NULL is passed.

Locking And Unlocking A Mutex :

Pthread  provides the following functions for locking & unlocking :

  • int pthread_mutex_lock(pthread_mutex_t *mutex);
    
    int pthread_mutex_unlock(pthread_mutex_t *mutex);

For eg. , to lock a mutex :

int abc = pthread_mutex_lock(&lock_a);
if (abc)
   {
       /* ERROR OCCURED */
      perror("pthhread_mutex_lock");
      pthread_exit(NULL);
   }

Destroying A Mutex :

After the use of mutex it should be destroyed. Once all the threads have finished using it , it can be destroyed using following function :  pthread_mutex_destroy() 

abc = pthread_mutex_destroy(&lock_a);

Leave a Reply