Advertisement
ludaludaed

QueueSpinLock

May 21st, 2023
962
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. //
  2. // Created by ludaludaed on 08.05.2023.
  3. //
  4.  
  5. #ifndef ALLIGATOR_SPIN_LOCK_H
  6. #define ALLIGATOR_SPIN_LOCK_H
  7.  
  8. #include <thread>
  9.  
  10. namespace lu {
  11.     class QueueSpinLock {
  12.         struct Node {
  13.             Node *next;
  14.             bool value;
  15.  
  16.             Node() : next(nullptr), value(false) {}
  17.         };
  18.  
  19.         friend class QueueSpinLockGuard;
  20.  
  21.     private:
  22.         void lock(Node *node) {
  23.             Node *prev_tail = tail_.exchange(node);
  24.             if (prev_tail != nullptr) {
  25.                 prev_tail->next = node;
  26.                 while (!node->value) {
  27.                     std::this_thread::yield();
  28.                 }
  29.             }
  30.         }
  31.  
  32.     public:
  33.         QueueSpinLock() : tail_(nullptr) {}
  34.  
  35.     private:
  36.         std::atomic<Node *> tail_;
  37.     };
  38.  
  39.     class QueueSpinLockGuard {
  40.     public:
  41.         explicit QueueSpinLockGuard(QueueSpinLock &lock) : lock_(lock) {
  42.             lock_.lock(&node_);
  43.         }
  44.  
  45.         ~QueueSpinLockGuard() {
  46.             if (node_.next != nullptr) {
  47.                 node_.next->value = true;
  48.             }
  49.         }
  50.  
  51.     private:
  52.         QueueSpinLock &lock_;
  53.         QueueSpinLock::Node node_;
  54.     };
  55. }
  56.  
  57. #endif //ALLIGATOR_SPIN_LOCK_H
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement