1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#pragma once #include <condition_variable> #include <deque> class Condition { public: Condition(); ~Condition(); void BeginSynchronized(); void EndSynchronized(); uint32_t Wait(time_t timeout); uint32_t Wait(); void Signal(); void Broadcast(); private: int m_nLockCount; std::condition_variable m_condition; std::mutex m_lock; }; |
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 |
#include "stdafx.h" #include "Condition.h" Condition::Condition() : m_nLockCount(0) {} void Condition::BeginSynchronized() { m_lock.lock(); ++m_nLockCount; } void Condition::EndSynchronized() { --m_nLockCount; m_lock.unlock(); } uint32_t Condition::Wait(time_t timeout) { std::unique_lock<std::mutex> lock(m_lock); m_condition.wait_for(lock, std::chrono::milliseconds(timeout)); return 0; } uint32_t Condition::Wait() { std::unique_lock<std::mutex> lock(m_lock); m_condition.wait(lock); return 0; } void Condition::Signal() { m_condition.notify_one(); } void Condition::Broadcast() { m_condition.notify_all(); } Condition::~Condition() {} |
Usage:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#pragma once #include "Condition.h" class RWLock { public: RWLock(); void AcquireReadLock(); void ReleaseReadLock(); void AcquireWriteLock(); void ReleaseWriteLock(); private: Condition _cond; volatile uint32_t _readers; volatile uint32_t _writers; }; |
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 |
#include "stdafx.h" #include "RWLock.h" RWLock::RWLock() { _readers = _writers = 0; } void RWLock::AcquireReadLock() { _cond.BeginSynchronized(); _readers++; _cond.EndSynchronized(); } void RWLock::ReleaseReadLock() { _cond.BeginSynchronized(); if (!(--_readers)) if (_writers) _cond.Signal(); _cond.EndSynchronized(); } void RWLock::AcquireWriteLock() { _cond.BeginSynchronized(); _writers++; if (_readers) _cond.Wait(); } void RWLock::ReleaseWriteLock() { if (--_writers) _cond.Signal(); _cond.EndSynchronized(); } |