Relative performance of swap vs compare-and-swap locks on x86

I assume atomic_swap(lockaddr, 1) gets translated to a xchg reg,mem instruction and atomic_compare_and_swap(lockaddr, 0, val) gets translated to a cmpxchg[8b|16b].

Some linux kernel developers think cmpxchg ist faster, because the lock prefix isn’t implied as with xchg. So if you are on a uniprocessor, multithread or can otherwise make sure the lock isn’t needed, you are probably better of with cmpxchg.

But chances are your compiler will translate it to a “lock cmpxchg” and in that case it doesn’t really matter.
Also note that while latencies for this instructions are low (1 cycle without lock and about 20 with lock), if you happen to use are common sync variable between two threads, which is quite usual, some additional bus cycles will be enforced, which last forever compared to the instruction latencies. These will most likely completly be hidden by a 200 or 500 cpu cycles long cache snoop/sync/mem access/bus lock/whatever.

Leave a Comment