<p>Lock-freedom provides what is called <em>progress guarantee</em>. You are right that in your example thread <code>A</code> has do perform a retry (i.e., loop again), but <em>only if some other thread changed the value</em>, which implies that that thread was able to make progress.</p>
<p>In contrast, a thread (let's call it <code>X</code>) that holds a spin-lock prevents all other threads from making progress until the lock is released. So if thread <code>X</code> is preempted, execution of all threads waiting for the lock is effectively stalled until <code>X</code> can resume execution and finally release the lock. If <code>X</code> were to be stalled indefinitely, then all other threads would also be blocked indefinitely.</p>
<p>Such a situation is not possible with lock-free algorithms, since it is guaranteed that at any time at least one thread can make progress.</p>
<hr />
<p>Which should be used depends on the situation. Lock-free algorithms are inherently difficult to design, especially for more complex data structures like trees. And even if you have a lock-free algorithm, it is almost always slower than a serial one, so a serial version protected by a lock might perform better. Then again, if the data structure is heavily contended, a lock-free version will scale better than one protected by a lock. However, if your workload is mostly read-only, a read-write-lock will also provide good scalability. Unfortunately, there is no general rule here...</p>
<hr />
<p>If you want to learn more about lock-freedom (and more) I recommend the book <a href="https://rads.stackoverflow.com/amzn/click/com/0123973376" rel="noreferrer" rel="nofollow noreferrer">The Art of Multiprocessor Programming</a>.<br />
If you prefer free alternatives I recommend <a href="https://arxiv.org/abs/1701.00854" rel="noreferrer">Is Parallel Programming Hard, And, If So, What Can You Do About It?</a> by Paul McKenney or <a href="https://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-579.pdf" rel="noreferrer">Practicallock-freedom</a> by Keir Fraser.</p>
What are the advantages of lock-free programming over spin lock？
<p>I am wondering which are the advantages of lock-free programming over spin lock？ I think that when we do lock free programming using CAS mechanism in a thread(called A), if other thread change the value in CAS, A thread still need to loop again. And I think it just like we use spin lock!</p>
<p>I am so confused about this. Although I know that CAS and spin-lock are suitable to use when the lock contention is not fierce, can someone explain in which scenarios lock free should be used and spin lock should be used?</p>