Multithreaded Programming Guide

Exit Print View

Updated: July 2014
 
 

Initialize a Mutex

Use mutex_init(3C) to initialize the mutex pointed to by mp. For POSIX threads, see Initializing a Mutex.

mutex_init(3C) Syntax

#include <synch.h> 
#include <thread.h>

int mutex_init(mutex_t *mp, int type, void *arg)); 

The type can be one of the following values.

  • USYNC_PROCESS. The mutex can be used to synchronize threads in this process and other processes. arg is ignored.

  • USYNC_PROCESS_ROBUST. The mutex can be used to robustly synchronize threads in this process and other processes. arg is ignored.

  • USYNC_THREAD. The mutex can be used to synchronize threads in this process only. arg is ignored.

When a process fails while holding a USYNC_PROCESS lock, subsequent requestors of that lock hang. This behavior is a problem for systems that share locks with client processes because the client processes can be abnormally killed. To avoid the problem of hanging on a lock held by a dead process, use USYNC_PROCESS_ROBUST to lock the mutex. USYNC_PROCESS_ROBUST adds two capabilities:

  • In the case of process death, all owned locks held by that process are unlocked.

  • The next requestor for any of the locks owned by the failed process receives the lock. But, the lock is held with an error return indicating that the previous owner failed while holding the lock.

Mutexes can also be initialized by allocation in zeroed memory, in which case a type of USYNC_THREAD is assumed.

Multiple threads must not initialize the same mutex simultaneously. A mutex lock must not be reinitialized while other threads might be using the mutex.

Mutexes With Intraprocess Scope
#include <thread.h>

mutex_t mp;
int ret;

/* to be used within this process only */
ret = mutex_init(&mp, USYNC_THREAD, 0); 
Mutexes With Interprocess Scope
#include <thread.h>

mutex_t mp;
int ret;

/* to be used among all processes */
ret = mutex_init(&mp, USYNC_PROCESS, 0); 
Mutexes With Interprocess Scope-Robust
#include <thread.h>

mutex_t mp;
int ret;

/* to be used among all processes */
ret = mutex_init(&mp, USYNC_PROCESS_ROBUST, 0); 

mutex_init Return Values

mutex_init() returns 0 if successful. When any of the following conditions is detected, mutex_init() fails and returns the corresponding value.

EFAULT

Description: mp points to an illegal address.

EINVAL

Description: The value specified by mp is invalid.

ENOMEM

Description: System has insufficient memory to initialize the mutex.

EAGAIN

Description: System has insufficient resources to initialize the mutex.

EBUSY

Description: System detected an attempt to reinitialize an active mutex.