Skip to content

Commit

Permalink
Introduce SpinMutex
Browse files Browse the repository at this point in the history
  • Loading branch information
Al2Klimov committed Aug 26, 2024
1 parent a8adfed commit b4c4202
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions lib/base/atomic.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,35 @@ class Atomic : public std::atomic<T> {
}
};

/**
* Classic spinlock mutex based on std::atomic_flag.
*
* @ingroup base
*/
class SpinMutex
{
public:
SpinMutex() = default;
SpinMutex(const SpinMutex&) = delete;
SpinMutex(SpinMutex&&) = delete;
SpinMutex& operator=(const SpinMutex&) = delete;
SpinMutex& operator=(SpinMutex&&) = delete;

void lock() noexcept
{
while (m_State.test_and_set(std::memory_order_acquire)) {
}
}

void unlock() noexcept
{
m_State.clear(std::memory_order_release);
}

private:
std::atomic_flag m_State = ATOMIC_FLAG_INIT;
};

/**
* Wraps any T into a std::atomic<T>-like interface that locks using a mutex.
*
Expand Down

0 comments on commit b4c4202

Please sign in to comment.