Lock a Mutex

The pthread_mutex_lock API is used to lock the mutex referenced by mutex.

Prototype:

int pthread_mutex_lock (pthread_mutex_t *mutex);
  • This API is used to lock the mutex object referenced by mutex.
  • If the mutex is already locked, the calling thread is blocked until the mutex becomes available.
  • Attempting to relock the mutex which is already locked causes deadlock, as the lock can be released by the thread which acquired the lock and that itself is blocked. Hence this should be considered while using mutex.

Return Values:
On success it returns 0 and on failure, an error code is returned.

Sample Code

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main()
{
    pthread_mutex_t mutex;
    int ret;
    int i = 5;
    
    ret = pthread_mutex_init (&mutex, NULL);
    if (ret)
    {
        printf ("\n Mutex initialization failed %s\n", strerror (errno));
        exit (EXIT_FAILURE);
    }
    printf ("\n Mutex initialization success\n");
    
    ret = pthread_mutex_lock (&mutex);
    if (ret)
    {
        printf ("\n Mutex lock failed %s\n", strerror (errno));
        exit (EXIT_FAILURE);
    }
    printf ("\n Mutex lock success\n");
    i++;
    pthread_mutex_unlock (&mutex);
    printf ("\n mutex unlock success\n"); 
    return 0;
}

output:


 gcc mutex_lock.c -o mutex_lock
 ./mutex_lock

 Mutex initialization success
 Mutex lock success
 mutex unlock success
...Program finished with exit code 0


Categories: Operating system (OS)

1 reply

Trackbacks

  1. Unlock a mutex - Tech Access

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: