Advertisement
Guest User

Untitled

a guest
Sep 2nd, 2014
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <atomic>
  3. #include <array>
  4. #include <thread>
  5.  
  6. template <typename T>
  7. struct node {
  8. T value;
  9. node* next{nullptr};
  10. };
  11.  
  12. typedef node<int> node_type;
  13.  
  14. std::atomic<node_type*> _begin;
  15.  
  16. node_type* get() {
  17. node_type* b = _begin;
  18.  
  19. while (!_begin.compare_exchange_weak(b, b->next))
  20. ;
  21.  
  22. return b;
  23. }
  24.  
  25. void give(node_type* v) {
  26. v->next = _begin;
  27.  
  28. while (!_begin.compare_exchange_weak(v->next, v))
  29. ;
  30. }
  31.  
  32. void get_and_give() {
  33. for (int i = 0; i < 1000000; ++i) {
  34. auto n = get();
  35.  
  36. give(n);
  37. }
  38. }
  39.  
  40. int main(int argc, const char * argv[])
  41. {
  42. std::array<node_type, 4> _nodes;
  43.  
  44. for (auto & i : _nodes)
  45. give(&i);
  46.  
  47. std::thread t1(get_and_give);
  48. std::thread t2(get_and_give);
  49. std::thread t3(get_and_give);
  50.  
  51. get_and_give();
  52.  
  53. t1.join();
  54. t2.join();
  55. t3.join();
  56.  
  57. return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement