CriticalSection vs Spinlock vs MutexSem

All of these objects are mutual exclusion objects. There aresome differences, both obvious and not so obvious.




The recursion capability of the CriticalSection and MutexSemobjects can be important when you have code called from multiple locations. A threadcan request ownership of these objects multiple times. Threads simply need to releasethe object the same number of times they requested ownership. This can make writingcode easier since you do not need to worry about if the object is already owned bythe thread when calling a procedure that will request ownership of the object. Aslong as all code that requests ownership also releases it, you are safe. There aretwo viewpoints about ownership recursion. Some say it is okay, and not say otherwise.

The spinlock is the least flexible of the three, but it is alsofastest. It is fast because no transition to the operating system kernel mode needsto occur, and because the compiler supports inline machine code intrinsic operationsused in implementing spinlocks. It is not flexible because it does not efficientlywait and generally does not support recursion. The CriticalSection is as nearly asfast as a spinlock and and also efficiently waits like a MutexSem. A CriticalSectionis a hybrid of a spinlock and a MutexSem. It will spin for a number iterations attemptingto obtain the lock, and then efficiently wait if the lock could not be obtained.The spinlock portion does not require a transition to the operating system, and thisis why a CriticalSection is fast. A MutexSem always makes a transition to the operatingsystem even when no wait is required.

Note: Remember that "fast" is a relative term.A MutexSem is "slow", only because other possibilities exist that are technicallyfaster. Generally only programs under very heavy load, such as server applications,would need to carefully consider the synchronization mechanisms used and the timethey consume.