Wildmeshing Toolkit
Loading...
Searching...
No Matches
spin_mutex.hpp
1#pragma once
2
3#include <atomic>
4#include <thread>
5
6namespace wmtk::threading {
7// ---------------------------------------------------------------------------
8// spin_mutex: replaces tbb::spin_mutex.
9// Movable/copyable (resets to unlocked) so it can live inside elements of a
10// std::vector that is grown single-threaded (e.g. the per-vertex mutex array).
11// ---------------------------------------------------------------------------
13{
14 std::atomic<bool> m_locked{false};
15
16public:
17 spin_mutex() = default;
18 spin_mutex(const spin_mutex&) noexcept {}
19 spin_mutex(spin_mutex&&) noexcept {}
20 spin_mutex& operator=(const spin_mutex&) noexcept { return *this; }
21 spin_mutex& operator=(spin_mutex&&) noexcept { return *this; }
22
23 void lock()
24 {
25 bool expected = false;
26 while (!m_locked.compare_exchange_weak(
27 expected,
28 true,
29 std::memory_order_acquire,
30 std::memory_order_relaxed)) {
31 expected = false;
32 std::this_thread::yield();
33 }
34 }
35
36 bool try_lock()
37 {
38 bool expected = false;
39 return m_locked.compare_exchange_strong(expected, true, std::memory_order_acquire);
40 }
41
42 void unlock() { m_locked.store(false, std::memory_order_release); }
43};
44
45} // namespace wmtk::threading
Definition spin_mutex.hpp:13