SharedThreadGlobals.cpp (1501B)
1 // Copyright (c) Microsoft Corporation. 2 // Licensed under the MIT License. 3 #include "pch.h" 4 #include "Public/winget/SharedThreadGlobals.h" 5 6 namespace AppInstaller::ThreadLocalStorage 7 { 8 using namespace AppInstaller::Logging; 9 10 static ThreadGlobals* SetOrGetThreadGlobals(bool setThreadGlobals, ThreadGlobals* pThreadGlobals = nullptr) 11 { 12 thread_local AppInstaller::ThreadLocalStorage::ThreadGlobals* t_pThreadGlobals = nullptr; 13 14 if (setThreadGlobals) 15 { 16 AppInstaller::ThreadLocalStorage::ThreadGlobals* previous_pThreadGlobals = t_pThreadGlobals; 17 t_pThreadGlobals = pThreadGlobals; 18 return previous_pThreadGlobals; 19 } 20 21 return t_pThreadGlobals; 22 } 23 24 std::unique_ptr<PreviousThreadGlobals> ThreadGlobals::SetForCurrentThread() 25 { 26 return std::make_unique<PreviousThreadGlobals>(SetOrGetThreadGlobals(true, this)); 27 } 28 29 ThreadGlobals* ThreadGlobals::GetForCurrentThread() 30 { 31 return SetOrGetThreadGlobals(false); 32 } 33 34 PreviousThreadGlobals::PreviousThreadGlobals(ThreadGlobals* previous) : m_previous(previous) 35 { 36 m_threadId = GetCurrentThreadId(); 37 } 38 39 PreviousThreadGlobals::~PreviousThreadGlobals() 40 { 41 // Not remaining on the same thread is a serious issue that must be resolved 42 FAIL_FAST_IF(GetCurrentThreadId() != m_threadId); 43 std::ignore = SetOrGetThreadGlobals(true, m_previous); 44 } 45 }