mirror of
https://github.com/trapexit/mergerfs.git
synced 2026-12-02 21:00:13 -05:00
80 lines
2 KiB
C++
80 lines
2 KiB
C++
|
|
/*
|
||
|
|
ISC License
|
||
|
|
|
||
|
|
Copyright (c) 2026, Antonio SJ Musumeci <trapexit@spawn.link>
|
||
|
|
|
||
|
|
Permission to use, copy, modify, and/or distribute this software for any
|
||
|
|
purpose with or without fee is hereby granted, provided that the above
|
||
|
|
copyright notice and this permission notice appear in all copies.
|
||
|
|
|
||
|
|
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||
|
|
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||
|
|
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||
|
|
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||
|
|
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||
|
|
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||
|
|
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||
|
|
*/
|
||
|
|
|
||
|
|
#pragma once
|
||
|
|
|
||
|
|
#include <atomic>
|
||
|
|
#include <shared_mutex>
|
||
|
|
|
||
|
|
|
||
|
|
/*
|
||
|
|
Writer-preferring reader/writer lock.
|
||
|
|
|
||
|
|
A pending exclusive acquisition gates new shared acquisitions, while
|
||
|
|
existing shared holders drain. It is usable with std::unique_lock and
|
||
|
|
std::shared_lock. As with other writer-preferring locks, the shared
|
||
|
|
side must not be acquired recursively: a waiting writer would then
|
||
|
|
deadlock against the same thread's first shared acquisition.
|
||
|
|
*/
|
||
|
|
class RWLock
|
||
|
|
{
|
||
|
|
public:
|
||
|
|
RWLock() = default;
|
||
|
|
RWLock(const RWLock&) = delete;
|
||
|
|
RWLock& operator=(const RWLock&) = delete;
|
||
|
|
|
||
|
|
public:
|
||
|
|
void
|
||
|
|
lock()
|
||
|
|
{
|
||
|
|
_writers.fetch_add(1);
|
||
|
|
_rwlock.lock();
|
||
|
|
}
|
||
|
|
|
||
|
|
void
|
||
|
|
unlock()
|
||
|
|
{
|
||
|
|
_rwlock.unlock();
|
||
|
|
if(_writers.fetch_sub(1) == 1)
|
||
|
|
_writers.notify_all();
|
||
|
|
}
|
||
|
|
|
||
|
|
void
|
||
|
|
lock_shared()
|
||
|
|
{
|
||
|
|
int writers;
|
||
|
|
|
||
|
|
while((writers = _writers.load()) != 0)
|
||
|
|
_writers.wait(writers);
|
||
|
|
|
||
|
|
_rwlock.lock_shared();
|
||
|
|
}
|
||
|
|
|
||
|
|
void
|
||
|
|
unlock_shared()
|
||
|
|
{
|
||
|
|
_rwlock.unlock_shared();
|
||
|
|
}
|
||
|
|
|
||
|
|
private:
|
||
|
|
std::shared_mutex _rwlock;
|
||
|
|
// Exclusive lockers waiting for or holding _rwlock. On its own cache
|
||
|
|
// line: shared lockers only read it, while they all write _rwlock.
|
||
|
|
alignas(64) std::atomic<int> _writers = 0;
|
||
|
|
};
|