Lock-free programming threads ને mutexes વગર coordinate કરે છે, atomic compare-and-swap (CAS) loops વાપરીને જેથી ઓછામાં ઓછો એક thread હંમેશા આગળ વધે ભલે બીજાં અટકે. કોઈ thread lock ધરાવતા બીજા દ્વારા block થઈ શકતું નથી.
CAS
Compare-and-swap atomically એક location ને નવી value પર ત્યારે જ set કરે છે જ્યારે તે હજુ અપેક્ષિત જૂની value ધરાવે છે; નહીંતર તે fail થાય છે અને તમે retry કરો છો. તે lock-free stacks, queues, અને counters પાછળનું primitive છે.
CAS(addr, expected, new):
if *addr == expected: *addr = new; return true # atomic, indivisible
else: return false
old, next;
{
old = value.get();
next = old + ;
} (!value.compareAndSet(old, next));
