Locks: Used thread_local to remove calls to GetCurrentThreadId (faster)

This commit is contained in:
Souryo 2016-01-26 17:21:33 -05:00
parent 50aed76ace
commit a68625c8ac
2 changed files with 11 additions and 20 deletions

View file

@ -1,30 +1,20 @@
#include "stdafx.h"
#include <assert.h>
#include "SimpleLock.h"
#ifdef WIN32
#include <Windows.h>
#endif
thread_local std::thread::id SimpleLock::_threadID = std::this_thread::get_id();
SimpleLock::SimpleLock()
{
_lock.clear();
_lockCount = 0;
_holderThreadID = ~0;
_holderThreadID = std::thread::id();
}
SimpleLock::~SimpleLock()
{
}
uint32_t SimpleLock::GetThreadId()
{
#ifdef WIN32
return GetCurrentThreadId();
#elif
return std::thread::id;
#endif
}
LockHandler SimpleLock::AcquireSafe()
{
return LockHandler(this);
@ -32,9 +22,9 @@ LockHandler SimpleLock::AcquireSafe()
void SimpleLock::Acquire()
{
if(_lockCount == 0 || _holderThreadID != GetThreadId()) {
if(_lockCount == 0 || _holderThreadID != _threadID) {
while(_lock.test_and_set());
_holderThreadID = GetThreadId();
_holderThreadID = _threadID;
_lockCount = 1;
} else {
//Same thread can acquire the same lock multiple times
@ -60,10 +50,10 @@ void SimpleLock::WaitForRelease()
void SimpleLock::Release()
{
if(_lockCount > 0 && _holderThreadID == GetThreadId()) {
if(_lockCount > 0 && _holderThreadID == _threadID) {
_lockCount--;
if(_lockCount == 0) {
_holderThreadID = ~0;
_holderThreadID = std::thread::id();
_lock.clear();
}
} else {

View file

@ -1,5 +1,6 @@
#pragma once
#include "stdafx.h"
#include <thread>
class SimpleLock;
@ -15,12 +16,12 @@ public:
class SimpleLock
{
private:
uint32_t _holderThreadID;
thread_local static std::thread::id _threadID;
std::thread::id _holderThreadID;
uint32_t _lockCount;
atomic_flag _lock;
uint32_t GetThreadId();
public:
SimpleLock();
~SimpleLock();