ClickHouse/src/Common/SharedMutex.h

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

53 lines
1.1 KiB
C++
Raw Normal View History

2023-01-09 14:58:44 +00:00
#pragma once
2023-01-11 12:23:33 +00:00
#include <shared_mutex>
2023-01-09 14:58:44 +00:00
#ifdef OS_LINUX /// Because of futex
#include <base/types.h>
2023-01-09 16:46:07 +00:00
#include <base/defines.h>
2023-01-09 14:58:44 +00:00
#include <atomic>
namespace DB
{
// Faster implementation of `std::shared_mutex` based on a pair of futexes
2023-01-09 16:46:07 +00:00
class TSA_CAPABILITY("SharedMutex") SharedMutex
2023-01-09 14:58:44 +00:00
{
public:
SharedMutex();
~SharedMutex() = default;
SharedMutex(const SharedMutex &) = delete;
SharedMutex & operator=(const SharedMutex &) = delete;
// Exclusive ownership
2023-01-09 16:46:07 +00:00
void lock() TSA_ACQUIRE();
bool try_lock() TSA_TRY_ACQUIRE(true);
void unlock() TSA_RELEASE();
2023-01-09 14:58:44 +00:00
// Shared ownership
2023-01-09 16:46:07 +00:00
void lock_shared() TSA_ACQUIRE_SHARED();
bool try_lock_shared() TSA_TRY_ACQUIRE_SHARED(true);
void unlock_shared() TSA_RELEASE_SHARED();
2023-01-09 14:58:44 +00:00
private:
static constexpr UInt64 readers = (1ull << 32ull) - 1ull; // Lower 32 bits of state
static constexpr UInt64 writers = ~readers; // Upper 32 bits of state
alignas(64) std::atomic<UInt64> state;
std::atomic<UInt32> waiters;
};
}
#else
2023-01-12 01:30:42 +00:00
namespace DB
{
2023-01-09 14:58:44 +00:00
using SharedMutex = std::shared_mutex;
}
#endif