I have been reading the book of Windows via C/C++. In chapter 8, page 215, the author compared the performance of various synchronization mechanisms. And I found the poor performance of mutex. When 4 threads run simultaneously, it spent more than twenty three seconds for the mutex synchronization.
Why is the Win32 mutex so time-consuming? And when can we use a mutex?
PS: I posted the test code in GitHub: https://gist.github.com/985198
Thanks for your replies.
A mutex in Win32 is a kernel object, meaning that every use of it (Wait, Release) requires a system call that switches into kernel mode and back to user mode. Plus if your thread actually has to wait for the mutex, it loses its quantum while another thread that can run gets scheduled on the CPU. On WinXP and earlier (and maybe some later versions of Windows), mutexes were "fair", meaning that if your thread was last to wait for a mutex, it would be the last to receive it, further increasing the potential for contention.
The reasons to use a mutex are that you can easily share them between processes, you can be notified when the thread owning it is killed, and you can wait on them along with other objects using WaitForMultipleObjects.
Note that your use of them in this benchmark is not the ideal way to use them because the overhead of just acquiring a mutex is way more than the amount of work you're doing.
Because mutexes are kernel objects, all operations on them require a context switch. Such operations are relatively expensive. The rule of thumb is that when you need share resources between threads in the same process, use CRITICAL_SECTION objects. When you need to share resources between threads in different processes, then use Win32 mutexes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With