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

View file

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