views:

103

answers:

3

In the following code.A mutex is initialized.what is the significance of NULL.

pthread_mutex_init(&a->monitor,NULL);

I want to know why we pass NULL as the second parameter.

+2  A: 

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.

Raghuram
@Raghuram- Thankyou
Pavitar
+6  A: 

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.

Zack
@ Zack- Thankyou
Pavitar
There is a list in the [POSIX `pthreads.h` spec](http://www.opengroup.org/onlinepubs/9699919799/basedefs/pthread.h.html) - see the functions starting with `pthread_mutexattr_`
caf
They are _not_ poorly standardised, IEEE/OG is on par with ISO re its standards. And most of the time, it's not useful, you're right about that. But there _are_ uses for them, however edgecase they may be.
paxdiablo
I must have been looking at an older version of 1003.1 that only defined the `pshared` property; so I assumed all the other functions in the (glibc) pthread.h on my system were GNU-only extensions. I'll revise "poorly standardized" to "not very portable" -- anything only in 1003.1-2008 is too new to rely on cross-platform, unfortunately.
Zack
+4  A: 

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.

paxdiablo