Mutex Initialization -(UNIX)
In the following code.A mutex is initialized.what is the significance of NULL开发者_如何学C.
pthread_mutex_init(&a->monitor,NULL);
I want to know why we pass NULL as the second parameter.
The second argument is a pointer to a pthread_mutexattr_t
structure, which lets you tweak the behavior of the mutex; NULL means "no special options here, use the default mutex behavior."
Most mutex options are useful only in edge cases (avoiding priority-inversion deadlocks, sharing a mutex between processes rather than threads) and the more useful ones (e.g. recursion control) were only standardized in the 2008 revision of POSIX, which means you can't yet rely on their existence cross-platform. paxdiablo's answer has a comprehensive list.
NULL
, as a mutex attribute, gives you an implementation defined default attribute. If you want to know what you can do with attributes, check out the following reference and follow the pthread_mutexattr_*
links in the SEE ALSO
section.
This is for issue 7 of the standard, 1003.1-2008. The starting point for that is here. Clicking on Headers
in the bottom left will allow you to navigate to the specific functionality (including pthreads.h
).
The attributes allow you to set or get:
- the type (deadlocking, deadlock-detecting, recursive, etc).
- the robustness (what happens when you acquire a mutex and the original owner died while possessing it).
- the process-shared attribute (for sharing a mutex across process boundaries).
- the protocol (how a thread behaves in terms of priority when a higher-priority thread wants the mutex).
- the priority ceiling (the priority at which the critical section will run, a way of preventing priority inversion).
And, of course, there's the init and destroy calls as well, not directly related to a specific attribute but used to create them.
The second argument of pthread_mutex_init takes the pthread_mutexattr_t as argument. You can use the second argument to specify the attributes to the mutex and if its NULL default mutex attributes are used.
精彩评论