Initialize a Mutex

The pthread_mutex API is used to initialize the mutex referenced by mutex with attributes specified by attr.

Prototype:

int pthread_mutex_init (pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
  • The first argument is the mutex that need to be initialized.
  • The second argument is the attribute pointer which can be NULL which is the same as passing the address of a default mutex attribute object or the mutex attribute that have already been set with pthread_mutexattr_int().
  • Statically defined mutexes can be initialized directly to have default attributes with the macro PTHREAD_MUTEX_INITIALIZER.
  • On successful initialization, the state of the mutex become initialized and unlocked.
  • A mutex lock must not be reinitialized or destroyed while other threads might be using it.

Return values:
It returns 0 on success, and on failure an error code is returned.

Sample Code:
To illustrate the initialization of mutex

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

int main()
{
    pthread_mutex_t mutex_default, mutex_recursive;
    pthread_mutexattr_t attr;
    pthread_mutexattr_settype (&attr,                     PTHREAD_MUTEX_RECURSIVE);
    int ret;
    
    ret = pthread_mutex_init (&mutex_default, NULL);
    if (ret)
    {
        printf ("\n Default Mutex initialization failed %s\n", strerror(errno));
        exit (EXIT_FAILURE);
    }
    printf ("\n Default Mutex initialization success\n");
    
    ret = pthread_mutex_init(&mutex_recursive, &attr);
    if (ret)
    {
        printf ("\n Recursive Mutex initialization failed %s\n", strerror(errno));
        exit (EXIT_FAILURE);
    }
    printf ("\n Recursive Mutex initialization success\n");
    return 0;
}

Output:


 gcc mutex_init.c -o mutex_int
 ./mutex_init

 Default Mutex initialization success

 Recursive Mutex initialization success


Categories: Operating system (OS)

1 reply

Trackbacks

  1. Lock 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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: