#pragma once
#include <wtf/Assertions.h>
#include <wtf/Atomics.h>
#include <wtf/Compiler.h>
#include <wtf/Noncopyable.h>
namespace WTF {
enum NoLockingNecessaryTag { NoLockingNecessary };
class AbstractLocker {
WTF_MAKE_NONCOPYABLE(AbstractLocker);
public:
AbstractLocker(NoLockingNecessaryTag)
{
}
protected:
AbstractLocker()
{
}
};
template <typename T> class Locker : public AbstractLocker {
public:
explicit Locker(T& lockable) : m_lockable(&lockable) { lock(); }
explicit Locker(T* lockable) : m_lockable(lockable) { lock(); }
Locker(NoLockingNecessaryTag) : m_lockable(nullptr) { }
Locker(int) = delete;
~Locker()
{
compilerFence();
if (m_lockable)
m_lockable->unlock();
}
static Locker tryLock(T& lockable)
{
Locker result(NoLockingNecessary);
if (lockable.tryLock()) {
result.m_lockable = &lockable;
return result;
}
return result;
}
explicit operator bool() const { return !!m_lockable; }
void unlockEarly()
{
m_lockable->unlock();
m_lockable = 0;
}
Locker(Locker&& other)
: m_lockable(other.m_lockable)
{
other.m_lockable = nullptr;
}
Locker& operator=(Locker&& other)
{
if (m_lockable)
m_lockable->unlock();
m_lockable = other.m_lockable;
other.m_lockable = nullptr;
return *this;
}
private:
void lock()
{
if (m_lockable)
m_lockable->lock();
compilerFence();
}
T* m_lockable;
};
template<typename LockType>
Locker<LockType> holdLock(LockType&) WARN_UNUSED_RETURN;
template<typename LockType>
Locker<LockType> holdLock(LockType& lock)
{
return Locker<LockType>(lock);
}
template<typename LockType>
Locker<LockType> holdLockIf(LockType&, bool predicate) WARN_UNUSED_RETURN;
template<typename LockType>
Locker<LockType> holdLockIf(LockType& lock, bool predicate)
{
return Locker<LockType>(predicate ? &lock : nullptr);
}
template<typename LockType>
Locker<LockType> tryHoldLock(LockType&) WARN_UNUSED_RETURN;
template<typename LockType>
Locker<LockType> tryHoldLock(LockType& lock)
{
return Locker<LockType>::tryLock(lock);
}
}
using WTF::AbstractLocker;
using WTF::Locker;
using WTF::NoLockingNecessaryTag;
using WTF::NoLockingNecessary;
using WTF::holdLock;
using WTF::holdLockIf;