Multithreaded Programming Guide

Similar Synchronization Functions-Mutual Exclusion Locks

Initialize a Mutex

mutex_init(3T)

#include <synch.h>   (or
#include <thread.h>)

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

Use mutex_init() to initialize the mutex pointed to by mp. The type can be one of the following (note that arg is currently ignored).

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 it.

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); 

Destroy a Mutex

mutex_destroy(3T)

#include <thread.h>

int mutex_destroy (mutex_t *mp);

Use mutex_destroy() to destroy any state associated with the mutex pointed to by mp. Note that the space for storing the mutex is not freed.

Acquire a Mutex

mutex_lock(3T)

#include <thread.h>

int mutex_lock(mutex_t *mp);

Use mutex_lock() to lock the mutex pointed to by mp. When the mutex is already locked, the calling thread blocks until the mutex becomes available (blocked threads wait on a prioritized queue).

Release a Mutex

mutex_unlock(3T)

#include <thread.h>

int mutex_unlock(mutex_t *mp);

Use mutex_unlock() to unlock the mutex pointed to by mp. The mutex must be locked and the calling thread must be the one that last locked the mutex (the owner).

Try to Acquire a Mutex

mutex_trylock(3T)

#include <thread.h>

int mutex_trylock(mutex_t *mp);

Use mutex_trylock() to attempt to lock the mutex pointed to by mp. This function is a nonblocking version of mutex_lock().