Advertisement
Guest User

Untitled

a guest
Jan 19th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. struct Data { Data(int i) :id(i) {} int id; };
  2.  
  3. class list
  4. {
  5. public:
  6. struct Node { std::shared_ptr<Data> d_; std::shared_ptr<Node> next; };
  7.  
  8. private:
  9. CRITICAL_SECTION update_lock;
  10. concurrency::concurrent_queue<std::shared_ptr<Data>> to_add;
  11. concurrency::concurrent_queue<int> to_remove;
  12. std::shared_ptr<Node> head;
  13. std::atomic_uint32_t count;
  14.  
  15. void push_back(std::shared_ptr<Data> d) {
  16. std::shared_ptr<Node> n = std::make_shared<Node>();
  17. n->d_ = std::move(d);
  18. n->next = head;
  19. while (!std::atomic_compare_exchange_weak(&head, &head, n)) {}
  20. count++;
  21. }
  22.  
  23. void remove(int id) {
  24. std::shared_ptr<Node> t_0 = nullptr;
  25. std::shared_ptr<Node> t_1 = head;
  26. while (1)
  27. {
  28. if (!t_1) break;
  29.  
  30. if (t_1->d_->id == id)
  31. {
  32. if (!t_0) { while (1) { if (std::atomic_compare_exchange_weak(&head, &head, head->next))break; } }
  33. else { while (1) { if (std::atomic_compare_exchange_weak(&t_0->next, &t_0->next, t_1->next))break; } }
  34.  
  35. t_1 = nullptr;
  36. count--;
  37. break;
  38. }
  39. t_0 = t_1;
  40. t_1 = t_1->next;
  41. }
  42. }
  43.  
  44.  
  45.  
  46.  
  47. public:
  48. list() : head(nullptr) { InitializeCriticalSection(&update_lock); }
  49. ~list() {
  50.  
  51. //clear the list
  52. while (head)
  53. {
  54. head = head->next;
  55. }
  56.  
  57. DeleteCriticalSection(&update_lock);
  58. }
  59.  
  60. uint32_t get_count() { return count.load(std::memory_order_relaxed); }
  61.  
  62. void add_remove(std::shared_ptr<Data> d, bool add) {
  63. if (add) to_add.push(std::move(d)); else to_remove.push(d->id);
  64.  
  65. unsigned char t_c = 0;
  66.  
  67. /*IMPORTANT-TO-GET: no. of instructions it takes for the function to exit the while_loop and leave the critical_section*/
  68. unsigned char n = 10;
  69.  
  70. while (1) {
  71. if (++t_c > n) return;
  72. if (TryEnterCriticalSection(&update_lock)) break;
  73. }
  74.  
  75.  
  76. std::shared_ptr<Data> temp = nullptr;
  77. while (1)
  78. {
  79. if (!to_add.try_pop(temp)) break;
  80. push_back(temp);
  81. }
  82.  
  83.  
  84. int temp_id;
  85. while (1)
  86. {
  87. if (!to_remove.try_pop(temp_id)) break;
  88. remove(temp_id);
  89. }
  90.  
  91. LeaveCriticalSection(&update_lock);
  92. }
  93.  
  94.  
  95. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement