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)
Leave a Reply