The CMPXCHG statement works as follows:
CMPXCHG (common, old, new):
int temp
temp <- common
if common = old then
common <- new
return temp
What is the simplest possible algorithm for implementing a critical section, if a CMPXCHG atomic instruction is available?
If you want to create a simple critical section (using the Windows definition of a
CRITICAL_SECTION
), you can look at the following pseduo-code:Then using it becomes a simple case of:
This acquisition is actually more like a try-to-acquire, to extend to to the more common acquisition scheme of CS's, we alter the method like so
This simple lock has its various issues, such as the inability to handle recursion, for which you need to keep a recursive lock count. I would recommend using something provided by the operating system. If you do need to write your own locks, Intel has a few publications on writing high-performance and scalable spinlocks, you can read one of them for Xeon processors here and another for x86 here. Lockless Inc also has an article on spinlocks here.