Mesen-SX/Utilities/SimpleLock.cpp

78 lines
1.1 KiB
C++
Raw Normal View History

2019-02-13 14:10:36 -05:00
#include "stdafx.h"
#include <assert.h>
#include "SimpleLock.h"
thread_local std::thread::id SimpleLock::_threadID = std::this_thread::get_id();
SimpleLock::SimpleLock()
{
_lock.clear();
_lockCount = 0;
_holderThreadID = std::thread::id();
}
SimpleLock::~SimpleLock()
{
}
LockHandler SimpleLock::AcquireSafe()
{
return LockHandler(this);
}
void SimpleLock::Acquire()
{
2020-12-19 23:32:47 +03:00
if (_lockCount == 0 || _holderThreadID != _threadID)
{
while (_lock.test_and_set());
2019-02-13 14:10:36 -05:00
_holderThreadID = _threadID;
_lockCount = 1;
2020-12-19 23:32:47 +03:00
}
else
{
2019-02-13 14:10:36 -05:00
//Same thread can acquire the same lock multiple times
_lockCount++;
}
}
bool SimpleLock::IsFree()
{
return _lockCount == 0;
}
void SimpleLock::WaitForRelease()
{
//Wait until we are able to grab a lock, and then release it again
Acquire();
Release();
}
void SimpleLock::Release()
{
2020-12-19 23:32:47 +03:00
if (_lockCount > 0 && _holderThreadID == _threadID)
{
2019-02-13 14:10:36 -05:00
_lockCount--;
2020-12-19 23:32:47 +03:00
if (_lockCount == 0)
{
2019-02-13 14:10:36 -05:00
_holderThreadID = std::thread::id();
_lock.clear();
}
2020-12-19 23:32:47 +03:00
}
else
{
2019-02-13 14:10:36 -05:00
assert(false);
}
}
2020-12-19 23:32:47 +03:00
LockHandler::LockHandler(SimpleLock* lock)
2019-02-13 14:10:36 -05:00
{
_lock = lock;
_lock->Acquire();
}
LockHandler::~LockHandler()
{
_lock->Release();
2020-12-19 23:32:47 +03:00
}