Reputation: 933
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.
Upvotes: 3
Views: 4416
Reputation: 86708
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.
Upvotes: 8
Reputation: 986
CRITICAL_SECTION is a spinlock which spins in userspace to acquire a lock. If it fails to get the lock at the end of spinning (limited by spin count), it gets into an wake-able wait (WaitForSingleObject()). Hence, for short sections of code you want to protect (critical section name comes from it) CRITICAL_SECTION is the way to go. If you plan to do IO and other time consuming tasks, CRITICAL_SECTION versus mutex/semaphore does not give you any savings.
Upvotes: 1
Reputation: 4887
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.
Upvotes: 8