4.3. Mutex Options
Procedure 4.1. Standard Mutex Creation
Note
- When you initialize a
pthread_mutex_t
object with the standard attributes, it will create a private, non-recursive, non-robust and non priority inheritance capable mutex. - Under pthreads, mutexes can be initialized with the following strings:
pthread_mutex_t my_mutex; pthread_mutex_init(&my_mutex, NULL);
- In this case, your application will not benefit from the advantages provided by the pthreads API and the Red Hat Enterprise Linux for Real Time kernel. There are a number of mutex options that must be considered when writing or porting an application.
Procedure 4.2. Advanced Mutex Options
pthread_mutexattr_t
object. This object will store the defined attributes for the futex.
Important
- Creating the mutex object:
pthread_mutex_t my_mutex; pthread_mutexattr_t my_mutex_attr; pthread_mutexattr_init(&my_mutex_attr);
- Shared and Private mutexes:Shared mutexes can be used between processes, however they can create a lot more overhead.
pthread_mutexattr_setpshared(&my_mutex_attr, PTHREAD_PROCESS_SHARED);
- Real-time priority inheritance:Priority inversion problems can be avoided by using priority inheritance.
pthread_mutexattr_setprotocol(&my_mutex_attr, PTHREAD_PRIO_INHERIT);
- Robust mutexes:Robust mutexes are released when the owner dies, however this can also come at a high overhead cost.
_NP
in this string indicates that this option is non-POSIX or not portable.pthread_mutexattr_setrobust_np(&my_mutex_attr, PTHREAD_MUTEX_ROBUST_NP);
- Mutex initialization:Once the attributes are set, initialize a mutex using those properties.
pthread_mutex_init(&my_mutex, &my_mutex_attr);
- Cleaning up the attributes object:After the mutex has been created, you can keep the attribute object in order to initialize more mutexes of the same type, or you can clean it up. The mutex is not affected in either case. To clean up the attribute object, use the
_destroy
command.pthread_mutexattr_destroy(&my_mutex_attr);
The mutex will now operate as a regularpthread_mutex
, and can be locked, unlocked and destroyed as normal.
For more information, or for further reading, the following man pages are related to the information given in this section.
- futex(7)
- pthread_mutex_destroy(P)For information on
pthread_mutex_t
andpthread_mutex_init
- pthread_mutexattr_setprotocol(3p)For information on
pthread_mutexattr_setprotocol
andpthread_mutexattr_getprotocol
- pthread_mutexattr_setprioceiling(3p)For information on
pthread_mutexattr_setprioceiling
andpthread_mutexattr_getprioceiling