4

why do we need lock prefix before CMPXCHG in intel architecture. please see for reference http://courses.engr.illinois.edu/ece390/archive/spr2002/books/labmanual/inst-ref-cmpxchg.html

what i am not sure what are the consequences if don,t use lock. because between loading the value into eax and exceuting LOCK CMPXCHG the value could be changed irrespective of the lock prefix because loading value into eax and LOCK CMPXCHG are two instructions.

Mean to say if i dont use CMPXCHG the worst thing could happen is that i have to spin again.

Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
veritas
  • 2,444
  • 1
  • 21
  • 30
  • @Evan Carroll why the question is duplicate when it has been asked before the other question – veritas Feb 01 '19 at 19:29
  • Because I evaluate quality, popularity, and contributions and the other question is in better form, massively more popular, and has Peter Cordes answer which is the SO equivalent of gold. Being first to ask is HUGE, but it's not 100% (if it was we wouldn't be allowed to dupe older questions onto newer ones). I did just give you an upvote though =) – Evan Carroll Feb 01 '19 at 19:35

1 Answers1

3
  • CMXCHG is truly atomic(asserts a bus lock) on a multiprocessor system only when it is prefixed with LOCK. These days snooping based cache coherence protocols are being used which eliminates the need for the fence(bus lock).
  • Coming to second part of the question(the value would anyways be changed). YES in that case the CMPXCHG instruction fails but nevertheless is still atomic with respect to all the processors.

Bottom line: Lock prefix makes the CMPXCHG a multiprocessor barrier instruction.

srikalyc
  • 54
  • 4