Do you really need a Windows Mutex?
Yes, the Windows Mutex will always work, but it introduces a kernel-level stall every time you create it. The thing takes about a full microsecond just to lock. And heaven help your app if there is lock contention.
It is like installing a stop sign in the middle of a race track. It will work at ensuring every process running on the computer obeys the lock, but at a terrible system-wide performance cost.
Wherever possible use a lockless solution or design around it. Don't get in the problem to begin with.
If you need to share data, don't lock and instead use atomic primitives.
If you need to share locked data, use an interlocked variable.
If you need to share more data than an interlocked variable can handle, use a critical section.
If you absolutely must coordinate data between many processes, use a system mutex.
The atomic operations and lockless solutions have no additional cost.
Interlocked operations cost around 5-10 nanoseconds, potentially a few more if there is contention.
Critical sections cost around 20-50 nanoseconds to enter and lock, plus potentially many microseconds (or worse) if there is contention.
A Windows Mutex costs around 500-1000 nanoseconds to enter and lock because it is done at the kernel level. It can take many milliseconds (or worse) if there is contention.
Choose the right synchronization objects for your needs. A full kernel-level Mutex object is usually the wrong selection.
Edited by frob, 30 May 2013 - 03:44 PM.