enh(ScopedLockWithUnlock): make it more alike std::unique_lock (#4652)

This commit is contained in:
siren186 2024-08-30 04:03:33 +08:00 committed by GitHub
parent 6d2b26645a
commit aa8084c6a0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 25 additions and 2 deletions

View File

@ -52,6 +52,7 @@ class Foundation_API Mutex: private MutexImpl
{
public:
using ScopedLock = Poco::ScopedLock<Mutex>;
using ScopedLockWithUnlock = Poco::ScopedLockWithUnlock<Mutex>;
Mutex();
/// creates the Mutex.
@ -107,6 +108,7 @@ class Foundation_API FastMutex: private FastMutexImpl
{
public:
using ScopedLock = Poco::ScopedLock<FastMutex>;
using ScopedLockWithUnlock = Poco::ScopedLockWithUnlock<FastMutex>;
FastMutex();
/// creates the Mutex.
@ -165,6 +167,7 @@ class Foundation_API SpinlockMutex
{
public:
using ScopedLock = Poco::ScopedLock<SpinlockMutex>;
using ScopedLockWithUnlock = Poco::ScopedLockWithUnlock<SpinlockMutex>;
SpinlockMutex();
/// Creates the SpinlockMutex.
@ -209,6 +212,7 @@ class Foundation_API NullMutex
{
public:
using ScopedLock = Poco::ScopedLock<NullMutex>;
using ScopedLockWithUnlock = Poco::ScopedLockWithUnlock<NullMutex>;
NullMutex()
/// Creates the NullMutex.

View File

@ -54,6 +54,7 @@ class Foundation_API NamedMutex: private NamedMutexImpl
{
public:
using ScopedLock = Poco::ScopedLock<NamedMutex>;
using ScopedLockWithUnlock = Poco::ScopedLockWithUnlock<NamedMutex>;
NamedMutex(const std::string& name);
/// creates the Mutex.

View File

@ -77,12 +77,18 @@ class ScopedLockWithUnlock
public:
explicit ScopedLockWithUnlock(M& mutex): _pMutex(&mutex)
{
poco_assert(_pMutex != nullptr);
_pMutex->lock();
_locked = true;
}
ScopedLockWithUnlock(M& mutex, long milliseconds): _pMutex(&mutex)
{
poco_assert(_pMutex != nullptr);
_pMutex->lock(milliseconds);
_locked = true;
}
~ScopedLockWithUnlock()
@ -97,17 +103,29 @@ public:
}
}
void lock()
{
poco_assert(_pMutex != nullptr);
poco_assert(_locked == false);
_pMutex->lock();
_locked = true;
}
void unlock()
{
if (_pMutex)
if (_locked)
{
poco_assert(_pMutex != nullptr);
_pMutex->unlock();
_pMutex = 0;
_locked = false;
}
}
private:
M* _pMutex;
bool _locked = false;
ScopedLockWithUnlock();
ScopedLockWithUnlock(const ScopedLockWithUnlock&);