CAS指令
bool CAS(T* p, T old, T new) {
if (*p != old) {
return false;
}
*p = new;
return true;
}
ABA问题
此处用到的stack代码如下:
#include <atomic>
class Node {
public:
int val;
Node *next;
Node(int val): val(val), next(NULL){
}
};
class Stack {
public:
void push(Node* new_top) {
while (true) {
Node *old_top = this->_top;
new_top->next = old_top;
// 将栈顶指针指向新节点,CAS 直到成功
if (this->_top.compare_exchange_weak(old_top, new_top)) {
return;}
}
}
Node* pop() {
while (true) {
Node *old_top = this->_top;
if (!old_top) return NULL;
Node *new_top = old_top->next;
// 将栈顶指针指向下一节点,CAS 直到成功
if (this->_top.compare_exchange_weak(old_top, new_top)) {
return old_top;}
}
}
private:
std::atomic<Node*> _top;
};
ABA问题的抽象描述:
- 线程1读了值a放在x,在准备用CAS修改值的前一刻被打断
- 线程2修改了a,改成了b,然后又改回了a
- 线程1调用CAS(a,x,new value),虽然能成功,但实际上这个a已经不是以前那个a了(值相同,但不是一个东西)