Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <twist/stdlike/atomic.hpp>
  4. #include <twist/threading/spin_wait.hpp>
  5.  
  6. namespace solutions {
  7.  
  8. /* QueueSpinLock spinlock;
  9. *
  10. * {
  11. * QueueSpinLock::Guard guard(spinlock); // Acquires spinlock
  12. * // Critical section starts here
  13. * } // Releases spinlock
  14. */
  15.  
  16. class QueueSpinLock {
  17. public:
  18. class Guard {
  19. public:
  20. explicit Guard(QueueSpinLock& spinlock) : spinlock_(spinlock) {
  21. Guard * prev_tail = spinlock_.tail_.exchange(this);
  22. if (prev_tail) {
  23. prev_tail->next_ = this;
  24. while(!owner_) {
  25. }
  26. }
  27. }
  28.  
  29. ~Guard() {
  30. Guard * cur = this;
  31. bool f = spinlock_.tail_.compare_exchange_strong(cur, nullptr);
  32. if (!f) {
  33. while (!next_) {
  34. }
  35. next_->owner_ = true;
  36. }
  37. }
  38.  
  39. private:
  40. QueueSpinLock& spinlock_;
  41. Guard * next_ = nullptr;
  42. bool owner_ = false;
  43. };
  44.  
  45. private:
  46. twist::atomic<Guard *> tail_ = nullptr;
  47. };
  48.  
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement