Thread Synchronization – Mutex Explained With Simple Example

A Mutex is basically a lock that is locked before accessing any critical section of code to ensure only one thread at a time can access it. Mutex is unlocked when the thread is done processing. Thus, mutex can also be thought as “Mutually exclusive flag” to ensure all other threads are blocked to a certain section of code when one thread is already accessing it.

Important Points

  • Mutex must be initialized before use.
  • Mutex locking function is a blocking call. Hence should be used judiciously.
  • Putting everything in mutex lock is not useful, it will defeat the benefits of multi-threading. Instead, only critical sections must be protected with mutexes.
  • Mutexes are only applicable between threads of a process. It’s not applicable between threads of different processes.
FunctionsUsage
pthread_mutex_initFunction to initialize the mutex.
PTHREAD_MUTEX_INITIALIZERMutex initializer applicable to statically allocated mutexes.
pthread_mutex_lock• Function to take the lock.
• Blocking Call
• Returns 0 if success else error code.
pthread_mutex_trylock• Function to take the lock.
• Non-Blocking call.
• Returns 0 if success else error code.
pthread_mutex_unlock• Function to release the lock
• Returns 0 if success else error code.
pthread_mutex_timedlock• Function to take the lock.
• Blocking call with a timeout value.
• Returns 0 if success else error code.
pthread_mutex helper functions

Example

Let’s have a look into sample program to illustrate mutex functionality.

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

pthread_mutex_t lock;
int counter = 0;

void* threadFun(void* arg)
{
    printf("Inside Thread function \n");

    pthread_mutex_lock(&lock);
    printf("Got the mutex Counter now: %d \n", counter);
    counter += 20;
    pthread_mutex_unlock(&lock);

    return NULL;
}


int main()
{
    pthread_t tid[2];
    

    if(pthread_mutex_init(&lock, NULL) != 0)
    {
        printf("Mutex initialization failed \n");
    }

    int i = 0;

    while (i < 2)
    {
        int error = pthread_create(&tid[i], NULL, &threadFun, NULL);
        if (error != 0)
        {
            printf("Thread Creation failed error code %d \n", error);
        }
        i++;
    }

    pthread_join(tid[0], NULL);
    pthread_join(tid[1], NULL);

    pthread_mutex_destroy(&lock);

    return 0;
}

Let’s check the output of above sample program.

Inside Thread function 
Got the mutex Counter now: 0 
Inside Thread function 
Got the mutex Counter now: 20 

Leave a Reply

Your email address will not be published. Required fields are marked *