Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // Created by ludaludaed on 08.05.2023.
- //
- #ifndef ALLIGATOR_SPIN_LOCK_H
- #define ALLIGATOR_SPIN_LOCK_H
- #include <thread>
- namespace lu {
- class QueueSpinLock {
- struct Node {
- Node *next;
- bool value;
- Node() : next(nullptr), value(false) {}
- };
- friend class QueueSpinLockGuard;
- private:
- void lock(Node *node) {
- Node *prev_tail = tail_.exchange(node);
- if (prev_tail != nullptr) {
- prev_tail->next = node;
- while (!node->value) {
- std::this_thread::yield();
- }
- }
- }
- public:
- QueueSpinLock() : tail_(nullptr) {}
- private:
- std::atomic<Node *> tail_;
- };
- class QueueSpinLockGuard {
- public:
- explicit QueueSpinLockGuard(QueueSpinLock &lock) : lock_(lock) {
- lock_.lock(&node_);
- }
- ~QueueSpinLockGuard() {
- if (node_.next != nullptr) {
- node_.next->value = true;
- }
- }
- private:
- QueueSpinLock &lock_;
- QueueSpinLock::Node node_;
- };
- }
- #endif //ALLIGATOR_SPIN_LOCK_H
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement