From a68625c8acb763ce775bd5648970099a2661e3b5 Mon Sep 17 00:00:00 2001 From: Souryo Date: Tue, 26 Jan 2016 17:21:33 -0500 Subject: [PATCH] Locks: Used thread_local to remove calls to GetCurrentThreadId (faster) --- Utilities/SimpleLock.cpp | 24 +++++++----------------- Utilities/SimpleLock.h | 7 ++++--- 2 files changed, 11 insertions(+), 20 deletions(-) diff --git a/Utilities/SimpleLock.cpp b/Utilities/SimpleLock.cpp index e263857a..5129986a 100644 --- a/Utilities/SimpleLock.cpp +++ b/Utilities/SimpleLock.cpp @@ -1,30 +1,20 @@ #include "stdafx.h" #include #include "SimpleLock.h" -#ifdef WIN32 - #include -#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 { diff --git a/Utilities/SimpleLock.h b/Utilities/SimpleLock.h index 09d6cd1c..630a3ab6 100644 --- a/Utilities/SimpleLock.h +++ b/Utilities/SimpleLock.h @@ -1,5 +1,6 @@ #pragma once #include "stdafx.h" +#include 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();