Saturday, February 6, 2016

CAS Compare And Swap Lock Free code pattern


Lock free changes to a global variable int _i can be achieved through <qatomic.h> QtAtomicInt and QAtomicPointer 

int _i=9;
void cas()
{
   int comp=_i;
    QAtomicInt atm(_i);
    while(! atm.testAndSetAcquire(comp,99,_i)){ comp=_i;}
    qDebug()<<comp<<" "<<atm<<"  "<<_i<<endl;
}

Note the single instruction must be inside a loop to ensure compare equal,then atomic update. and if not equal then update comp first.

Acquire and Release (Ordered=A+R) build a Memory Barriers so that CPU and optimizer cannot move instruction up or down out of the code block:

QAtomicPointer<<int> p;

p.fetchAnd?Acquire(&_i);
...//  inside Memory Barrier
p.fetchAnd?Rlease(&_i);

?=Add or Store.

No comments:

Post a Comment