fork(1) download
  1. #include <atomic>
  2.  
  3. template<typename T>
  4. class List {
  5. public:
  6. void append(const T& value); // see below
  7.  
  8. private:
  9. struct Node {
  10. T data;
  11. Node *next;
  12. };
  13.  
  14. std::atomic<Node*> head;
  15. };
  16.  
  17. template<typename T>
  18. void List<T>::append(const T& value)
  19. {
  20. Node *newNode = new Node { value };
  21.  
  22. Node* headNode;
  23. do {
  24. headNode = head;
  25. newNode->next = head;
  26. } while (!std::atomic_compare_exchange_weak(&head, &headNode, newNode));
  27. // or while (!head.compare_exchange_weak(headNode, newNode));
  28. }
  29.  
  30. int main()
  31. {
  32. List<int> li;
  33. li.append(10);
  34. }
  35.  
Success #stdin #stdout 0s 2980KB
stdin
Standard input is empty
stdout
Standard output is empty