views:

492

answers:

3

Windows Mutex seems to allow an acquired lock to be acquired again (recursively) if the thread currently owning the lock tries to acquire it.

But, posix based pthread locks don't allow such a behaviour.

Is there any compile time macro or any settings which can make the windows mutex behave in the same way as the pthread mutex?

A: 

Have a look at this article under 'fast mutex'.

topic7">http://msdn.microsoft.com/en-us/library/ms810047.aspx#locks_topic7

These type of mutex'es cannot be recursively acquired.

Off course, you'd have to look into how to implement them in C.

Tony
The Fast Mutex support is intended for drivers, not user-mode code.
gavinb
+1  A: 

As long as you program in Windows, avoid reimplementing the behavior of its Mutex. It being re-entrant by the same thread is absolutely essential for its defined behavior.

A sync object without thread affinity is a semaphore that counts to 1. Use CreateSemaphore().

Fwiw, it is very curious that you need this kind of behavior. It sounds like you are trying to use the same sync object in multiple places inappropriately. You can use the semaphore but you'll lose concurrency potential. Consider using more than one mutex instead.

Hans Passant
Actually, I have this problem related to come legacy code and I want to resolve it without changing much of the logic. So, wanted to know if the behaviour can be altered. My code should work in multiple OS, so I want the behaviour to remain same across all the OS."It sounds like you are trying to use the same sync object in multiple places inappropriately." - Yes. It is case of negative scenario. I just want the behaviour to be same in all OS in the negative scenario. Thanks for your reply!
Jay
Well, use a boost semaphore. Multi-platform and non-reentrant.
Hans Passant
+1  A: 

You cannot alter the fact that Windows Mutexes are recursive. And while Posix threads are not recursive by default, you can use pthread_mutexattr_settype() with the PTHREAD_MUTEX_RECURSIVE flag to make one so.

Locking a mutex in Windows is actually quite an expensive operation, and best suited to inter-process synchronisation. For a mutex used only within a single process, a critical section is normally used, however these are re-entrant also. As nobugz states, you would need to use a semaphore, initialised with a maximum count of 1, to get non-recursive synchronisation.

A semaphore object is like a special counter, that can be atomically incremented and decremented across threads (or processes, if created shared). By creating one with a maximum count of 1, you get the non-recursive behaviour you require.

gavinb
Critical Section CAN be entered again from the same thread. http://msdn.microsoft.com/en-us/library/ms682608(VS.85).aspx
arke
Thanks for catching that oops - fixed answer accordingly.
gavinb