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 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

你可能感兴趣的:(C++,11,c++)