std::atomic::compare_exchange_weak

https://www.cplusplus.com/reference/atomic/atomic/compare_exchange_weak/
https://github.com/apache/incubator-brpc/blob/master/docs/cn/atomic_instructions.md

#include // std::cout
#include // std::atomic
#include // std::thread
#include // std::vector

// a simple global linked list:
struct Node { int value; Node* next; };
std::atomic<Node*> list_head (nullptr);

void append (int val) { // append an element to the list
Node* oldHead = list_head;
Node* newNode = new Node {val,oldHead};

// what follows is equivalent to: list_head = newNode, but in a thread-safe way
/* 如果oldHead等于list_head,完成头结点链接到新建的节点;反之,同时有另一个线程在链接过程插入,则更新该线程的头结点为新建节点 */
while (!list_head.compare_exchange_weak(oldHead,newNode))
newNode->next = oldHead;
}

int main ()
{
// spawn 10 threads to fill the linked list:
std::vectorstd::thread threads;
for (int i=0; i<10; ++i) threads.push_back(std::thread(append,i));
for (auto& th : threads) th.join();

// print contents:
for (Node* it = list_head; it!=nullptr; it=it->next)
std::cout << ’ ’ << it->value;
std::cout << ‘\n’;

// cleanup:
Node* it; while (it=list_head) {list_head=it->next; delete it;}
return 0;
}

  std::atomic<int> ai(3);// 注意most vexing parse
  ai.store(10);
  int expected = 1;
  int val = 100;
  cout << ai.compare_exchange_weak(expected, val) << endl;//0
  std::cout << ai.load() << std::endl;//10
  std::cout << expected << std::endl;//10

  cout << ai.compare_exchange_strong(expected, val) << endl;//1
  std::cout << ai.load() << std::endl;//100
  std::cout << expected << std::endl;//10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值