| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
#pragma once |
| 5 |
|
| 6 |
#include <atomic> |
| 7 |
#include <cassert> |
| 8 |
#include <cstdint> |
| 9 |
|
| 10 |
namespace Common |
| 11 |
{ |
| 12 |
|
| 13 |
class TransferableSharedMutex |
| 14 |
{ |
| 15 |
public: |
| 16 |
void lock() |
| 17 |
{ |
| 18 |
while (true) |
| 19 |
{ |
| 20 |
CounterType old_value{}; |
| 21 |
if (m_counter.compare_exchange_strong(old_value, EXCLUSIVE_LOCK_VALUE, |
| 22 |
std::memory_order_acquire, std::memory_order_relaxed)) |
| 23 |
{ |
| 24 |
return; |
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
m_counter.wait(old_value, std::memory_order_relaxed); |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
bool try_lock() |
| 34 |
{ |
| 35 |
CounterType old_value{}; |
| 36 |
return m_counter.compare_exchange_weak(old_value, EXCLUSIVE_LOCK_VALUE, |
| 37 |
std::memory_order_acquire, std::memory_order_relaxed); |
| 38 |
} |
| 39 |
|
| 40 |
void unlock() |
| 41 |
{ |
| 42 |
m_counter.store(0, std::memory_order_release); |
| 43 |
m_counter.notify_all(); |
| 44 |
} |
| 45 |
|
| 46 |
void lock_shared() |
| 47 |
{ |
| 48 |
while (true) |
| 49 |
{ |
| 50 |
auto old_value = m_counter.load(std::memory_order_relaxed); |
| 51 |
while (old_value < LAST_SHARED_LOCK_VALUE) |
| 52 |
{ |
| 53 |
if (m_counter.compare_exchange_strong(old_value, old_value + 1, std::memory_order_acquire, |
| 54 |
std::memory_order_relaxed)) |
| 55 |
{ |
| 56 |
return; |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
assert(old_value != LAST_SHARED_LOCK_VALUE); |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
m_counter.wait(old_value, std::memory_order_relaxed); |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
bool try_lock_shared() |
| 70 |
{ |
| 71 |
auto old_value = m_counter.load(std::memory_order_relaxed); |
| 72 |
return (old_value < LAST_SHARED_LOCK_VALUE) && |
| 73 |
m_counter.compare_exchange_weak(old_value, old_value + 1, std::memory_order_acquire, |
| 74 |
std::memory_order_relaxed); |
| 75 |
} |
| 76 |
|
| 77 |
void unlock_shared() |
| 78 |
{ |
| 79 |
if (m_counter.fetch_sub(1, std::memory_order_release) == 1) |
| 80 |
m_counter.notify_one(); |
| 81 |
} |
| 82 |
|
| 83 |
private: |
| 84 |
using CounterType = std::uintptr_t; |
| 85 |
|
| 86 |
static constexpr auto EXCLUSIVE_LOCK_VALUE = CounterType(-1); |
| 87 |
static constexpr auto LAST_SHARED_LOCK_VALUE = EXCLUSIVE_LOCK_VALUE - 1; |
| 88 |
|
| 89 |
std::atomic<CounterType> m_counter{}; |
| 90 |
}; |
| 91 |
|
| 92 |
} |