File size: 3,703 Bytes
bfd87b5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/core/Core_EXPORTS.h>
#include <aws/core/utils/threading/Semaphore.h>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <cstdint>
namespace Aws
{
namespace Utils
{
namespace Threading
{
/**
* This lock is optimized for frequent reads and infrequent writes.
* However, writers get priority to the lock.
*/
class AWS_CORE_API ReaderWriterLock
{
public:
ReaderWriterLock();
/**
* Enters the lock in Reader-mode.
* This call blocks until no writers are acquiring the lock.
*/
void LockReader();
/**
* Decrements the readers count by one and if the count is zero, signals any waiting writers to acquire
* the lock.
* NOTE: Calling this function without a matching LockReader results in undefined behavior.
*/
void UnlockReader();
/**
* Enters the lock in Writer-mode.
* This call blocks until no readers nor writers are acquiring the lock.
*/
void LockWriter();
/**
* Decrements the number of writers by one and signals any waiting readers or writers to acquire the
* lock.
* NOTE: Calling this function without a matching LockWriter results in undefined behavior.
*/
void UnlockWriter();
private:
std::atomic<int64_t> m_readers;
std::atomic<int64_t> m_holdouts;
Semaphore m_readerSem;
Semaphore m_writerSem;
std::mutex m_writerLock;
};
class AWS_CORE_API ReaderLockGuard
{
public:
explicit ReaderLockGuard(ReaderWriterLock& rwl) : m_rwlock(rwl), m_upgraded(false)
{
m_rwlock.LockReader();
}
void UpgradeToWriterLock()
{
m_rwlock.UnlockReader();
m_rwlock.LockWriter();
m_upgraded = true;
}
~ReaderLockGuard()
{
if(m_upgraded)
{
m_rwlock.UnlockWriter();
}
else
{
m_rwlock.UnlockReader();
}
}
// for VS2013
ReaderLockGuard(const ReaderLockGuard&) = delete;
ReaderLockGuard& operator=(const ReaderLockGuard&) = delete;
private:
ReaderWriterLock& m_rwlock;
bool m_upgraded;
};
class AWS_CORE_API WriterLockGuard
{
public:
explicit WriterLockGuard(ReaderWriterLock& rwl) : m_rwlock(rwl)
{
m_rwlock.LockWriter();
}
~WriterLockGuard()
{
m_rwlock.UnlockWriter();
}
// for VS2013
WriterLockGuard(const WriterLockGuard&) = delete;
WriterLockGuard& operator=(const WriterLockGuard&) = delete;
private:
ReaderWriterLock& m_rwlock;
};
}
}
}
|