Unlock a Mutex

The pthread_mutex_unlock() API is used to unblock the mutex reference by mutex.

Prototype:

int pthread_mutex_unlock (pthread_mutex_t *mutex);
  • The pthread_mutex_unlock() function releases the mutex object referenced by mutex.
  • The manner in which a mutex is released is dependent upon the mutex type attribute. If there are threads blocked on the mutex object referenced by mutex when pthread_mutex_unlock() is called, resulting in the mutex becoming available

Return Value:
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_unlock
 ./mutex_unlock

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


Categories: Operating system (OS)

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: