本文最后更新于6 天前,其中的信息可能已经过时,如有错误请留言
原子类型的基本操作:
#include <atomic>
#include <iostream>
int main() {
std::atomic<int> a{0};
std::cout << a.load() << std::endl;
a.store(1);
std::cout << a.load() << std::endl;
std::cout << a.exchange(2) << std::endl;
std::cout << a.load() << std::endl;
a = 3;
std::cout << a << std::endl;
a.fetch_add(1);
std::cout << a.load() << std::endl;
a.fetch_sub(1);
std::cout << a.load() << std::endl;
a++;
std::cout << a.load() << std::endl;
a--;
std::cout << a.load() << std::endl;
return 0;
}
输出:
[porco@poyun183010267861 Algorithm]$ ./main
0
1
1
2
3
4
3
4
3
原子类型的CAS操作(compare_exchange_strong与compare_exchange_weak):
// 循环尝试用compare_exchange_weak
Node* old_head = head.load();
Node* new_head = new Node(...);
do {
new_head->next = old_head;
} while (!head.compare_exchange_weak(old_head, new_head));
// 如果失败,old_head 会被更新为最新的 head,再重试
// 一次性尝试用compare_exchange_strong
int expected = 0;
if (a.compare_exchange_strong(expected, 1)) {
// 成功:a 从 0 改成 1
} else {
// 失败:expected 被更新为当前值
}
如果a的值与expected相等,则返回true,将新的值写入。如果a的值与expected不想等,则说明,a的值在此期间被修改过,返回false,不能直接修改,要重试尝试。
例如修改链表头节点head的例子,如果head的值在修改的时候,不是old_head,说明head刚刚被其他线程修改了,那么new_head->next必须修改为新的head,compare_exchange_weak会把head的最新值写入到old_head中。


