Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <twist/stdlike/atomic.hpp>
- #include <twist/threading/spin_wait.hpp>
- namespace solutions {
- /* QueueSpinLock spinlock;
- *
- * {
- * QueueSpinLock::Guard guard(spinlock); // Acquires spinlock
- * // Critical section starts here
- * } // Releases spinlock
- */
- class QueueSpinLock {
- public:
- class Guard {
- public:
- explicit Guard(QueueSpinLock& spinlock) : spinlock_(spinlock) {
- Guard * prev_tail = spinlock_.tail_.exchange(this);
- if (prev_tail) {
- prev_tail->next_ = this;
- while(!owner_) {
- }
- }
- }
- ~Guard() {
- Guard * cur = this;
- bool f = spinlock_.tail_.compare_exchange_strong(cur, nullptr);
- if (!f) {
- while (!next_) {
- }
- next_->owner_ = true;
- }
- }
- private:
- QueueSpinLock& spinlock_;
- Guard * next_ = nullptr;
- bool owner_ = false;
- };
- private:
- twist::atomic<Guard *> tail_ = nullptr;
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement