eathread_thread_pc.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // Copyright (c) Electronic Arts Inc. All rights reserved.
  3. ///////////////////////////////////////////////////////////////////////////////
  4. #include "EABase/eabase.h"
  5. #include "eathread/eathread.h"
  6. #include "eathread/eathread_callstack.h"
  7. #include "eathread/eathread_mutex.h"
  8. #include "eathread/eathread_sync.h"
  9. #include "eathread/eathread_thread.h"
  10. #include "eathread/internal/eathread_global.h"
  11. #if defined(EA_COMPILER_MSVC) && EA_COMPILER_VERSION >= 1900 // VS2015+
  12. // required for windows.h that has mismatch that is included in this file
  13. EA_DISABLE_VC_WARNING(5031 5032)// #pragma warning(pop): likely mismatch, popping warning state pushed in different file / detected #pragma warning(push) with no corresponding
  14. #endif
  15. // Warning 6312 and 6322 are spurious, as we are not execution a case that could possibly loop.
  16. // 6312: Possible infinite loop: use of the constant EXCEPTION_CONTINUE_EXECUTION in the exception-filter expression of a try-except. Execution restarts in the protected block
  17. // 6322: Empty _except block
  18. EA_DISABLE_VC_WARNING(6312 6322)
  19. #if defined(EA_PLATFORM_MICROSOFT) && !EA_POSIX_THREADS_AVAILABLE
  20. #include <new>
  21. #include <process.h>
  22. EA_DISABLE_ALL_VC_WARNINGS()
  23. #include <Windows.h>
  24. EA_RESTORE_ALL_VC_WARNINGS()
  25. #if defined(EA_COMPILER_MSVC)
  26. struct ThreadNameInfo{
  27. DWORD dwType;
  28. LPCSTR lpName;
  29. DWORD dwThreadId;
  30. DWORD dwFlags;
  31. };
  32. extern "C" WINBASEAPI DWORD WINAPI SetThreadIdealProcessor(_In_ HANDLE hThread, _In_ DWORD dwIdealProcessor);
  33. extern "C" WINBASEAPI BOOL WINAPI IsDebuggerPresent();
  34. #endif
  35. #ifdef EA_COMPILER_MSVC
  36. // We are changing the initalization ordering here because in bulkbuild tool builds the initialization
  37. // order of globals changes and causes a crash when we attempt to lock the Mutex guarding access
  38. // of the EAThreadDynamicData objects. The code attempts to lock a mutex that has been destructed
  39. // and causes a crash within the WindowsSDK. This ensures that global mutex object is not destructed
  40. // until all user code has destructed.
  41. //
  42. #ifndef EATHREAD_INIT_SEG_DEFINED
  43. #define EATHREAD_INIT_SEG_DEFINED
  44. // warning C4075: initializers put in unrecognized initialization area
  45. //warning C4073: initializers put in library initialization area
  46. EA_DISABLE_VC_WARNING(4075 4073)
  47. #pragma init_seg(lib)
  48. #define WARNING_INIT_SEG_PUSHED
  49. #endif
  50. #endif
  51. namespace EA {
  52. namespace Thread {
  53. extern void SetCurrentThreadHandle(HANDLE hThread, bool bDynamic);
  54. namespace Internal { extern void SetThreadName(EAThreadDynamicData* pTDD, const char* pName); };
  55. }
  56. }
  57. namespace EA
  58. {
  59. namespace Thread
  60. {
  61. extern Allocator* gpAllocator;
  62. static AtomicInt32 nLastProcessor = 0;
  63. const size_t kMaxThreadDynamicDataCount = 128;
  64. struct EAThreadGlobalVars
  65. {
  66. EA_PREFIX_ALIGN(8)
  67. char gThreadDynamicData[kMaxThreadDynamicDataCount][sizeof(EAThreadDynamicData)] EA_POSTFIX_ALIGN(8);
  68. AtomicInt32 gThreadDynamicDataAllocated[kMaxThreadDynamicDataCount];
  69. Mutex gThreadDynamicMutex;
  70. EAThreadGlobalVars() {}
  71. EAThreadGlobalVars(const EAThreadGlobalVars&) {}
  72. EAThreadGlobalVars& operator=(const EAThreadGlobalVars&) {}
  73. };
  74. EATHREAD_GLOBALVARS_CREATE_INSTANCE;
  75. EAThreadDynamicData* AllocateThreadDynamicData()
  76. {
  77. AutoMutex am(EATHREAD_GLOBALVARS.gThreadDynamicMutex);
  78. for(size_t i(0); i < kMaxThreadDynamicDataCount; i++)
  79. {
  80. if(EATHREAD_GLOBALVARS.gThreadDynamicDataAllocated[i].SetValueConditional(1, 0))
  81. return (EAThreadDynamicData*)EATHREAD_GLOBALVARS.gThreadDynamicData[i];
  82. }
  83. // This is a safety fallback mechanism. In practice it won't be used in almost all situations.
  84. if(gpAllocator)
  85. return (EAThreadDynamicData*)gpAllocator->Alloc(sizeof(EAThreadDynamicData));
  86. else
  87. return new EAThreadDynamicData; // This is a small problem, as this doesn't just allocate it but also constructs it.
  88. }
  89. void FreeThreadDynamicData(EAThreadDynamicData* pEAThreadDynamicData)
  90. {
  91. AutoMutex am(EATHREAD_GLOBALVARS.gThreadDynamicMutex);
  92. if((pEAThreadDynamicData >= (EAThreadDynamicData*)EATHREAD_GLOBALVARS.gThreadDynamicData) && (pEAThreadDynamicData < ((EAThreadDynamicData*)EATHREAD_GLOBALVARS.gThreadDynamicData + kMaxThreadDynamicDataCount)))
  93. {
  94. pEAThreadDynamicData->~EAThreadDynamicData();
  95. EATHREAD_GLOBALVARS.gThreadDynamicDataAllocated[pEAThreadDynamicData - (EAThreadDynamicData*)EATHREAD_GLOBALVARS.gThreadDynamicData].SetValue(0);
  96. }
  97. else
  98. {
  99. // Assume the data was allocated via the fallback mechanism.
  100. if(gpAllocator)
  101. {
  102. pEAThreadDynamicData->~EAThreadDynamicData();
  103. gpAllocator->Free(pEAThreadDynamicData);
  104. }
  105. else
  106. delete pEAThreadDynamicData;
  107. }
  108. }
  109. EAThreadDynamicData* FindThreadDynamicData(ThreadId threadId)
  110. {
  111. for(size_t i(0); i < kMaxThreadDynamicDataCount; i++)
  112. {
  113. EAThreadDynamicData* const pTDD = (EAThreadDynamicData*)EATHREAD_GLOBALVARS.gThreadDynamicData[i];
  114. if(pTDD->mhThread == threadId)
  115. return pTDD;
  116. }
  117. return NULL; // This is no practical way we can find the data unless thread-specific storage was involved.
  118. }
  119. EAThreadDynamicData* FindThreadDynamicData(EA::Thread::SysThreadId sysThreadId)
  120. {
  121. for (size_t i(0); i < kMaxThreadDynamicDataCount; ++i)
  122. {
  123. EAThreadDynamicData* const pTDD = (EAThreadDynamicData*)EATHREAD_GLOBALVARS.gThreadDynamicData[i];
  124. if (pTDD->mnThreadId == sysThreadId)
  125. return pTDD;
  126. }
  127. return nullptr; // This is no practical way we can find the data unless thread-specific storage was involved.
  128. }
  129. bool IsDebuggerPresent()
  130. {
  131. #if defined(EA_PLATFORM_MICROSOFT)
  132. return ::IsDebuggerPresent() != 0;
  133. #else
  134. return false;
  135. #endif
  136. }
  137. }
  138. }
  139. EAThreadDynamicData::EAThreadDynamicData()
  140. : mhThread(EA::Thread::kThreadIdInvalid),
  141. mnThreadId(0), // Note that this is a Windows "thread id", wheras for us thread ids are what Windows calls a thread handle.
  142. mnStatus(EA::Thread::Thread::kStatusNone),
  143. mnReturnValue(0),
  144. mpBeginThreadUserWrapper(NULL),
  145. mnRefCount(0)
  146. {
  147. // Empty
  148. }
  149. EAThreadDynamicData::~EAThreadDynamicData()
  150. {
  151. if(mhThread)
  152. ::CloseHandle(mhThread);
  153. mhThread = EA::Thread::kThreadIdInvalid;
  154. mnThreadId = 0;
  155. }
  156. void EAThreadDynamicData::AddRef()
  157. {
  158. mnRefCount.Increment();
  159. }
  160. void EAThreadDynamicData::Release()
  161. {
  162. if(mnRefCount.Decrement() == 0)
  163. EA::Thread::FreeThreadDynamicData(this);
  164. }
  165. EA::Thread::ThreadParameters::ThreadParameters()
  166. : mpStack(NULL)
  167. , mnStackSize(0)
  168. , mnPriority(kThreadPriorityDefault)
  169. , mnProcessor(kProcessorDefault)
  170. , mnAffinityMask(kThreadAffinityMaskAny)
  171. , mpName("")
  172. , mbDisablePriorityBoost(false)
  173. {
  174. }
  175. EA::Thread::RunnableFunctionUserWrapper EA::Thread::Thread::sGlobalRunnableFunctionUserWrapper = NULL;
  176. EA::Thread::RunnableClassUserWrapper EA::Thread::Thread::sGlobalRunnableClassUserWrapper = NULL;
  177. EA::Thread::AtomicInt32 EA::Thread::Thread::sDefaultProcessor = kProcessorAny;
  178. EA::Thread::AtomicUint64 EA::Thread::Thread::sDefaultProcessorMask = UINT64_C(0xffffffffffffffff);
  179. EA::Thread::RunnableFunctionUserWrapper EA::Thread::Thread::GetGlobalRunnableFunctionUserWrapper()
  180. {
  181. return sGlobalRunnableFunctionUserWrapper;
  182. }
  183. void EA::Thread::Thread::SetGlobalRunnableFunctionUserWrapper(EA::Thread::RunnableFunctionUserWrapper pUserWrapper)
  184. {
  185. if(sGlobalRunnableFunctionUserWrapper != NULL)
  186. {
  187. // Can only be set once in entire game.
  188. EAT_ASSERT(false);
  189. }
  190. else
  191. {
  192. sGlobalRunnableFunctionUserWrapper = pUserWrapper;
  193. }
  194. }
  195. EA::Thread::RunnableClassUserWrapper EA::Thread::Thread::GetGlobalRunnableClassUserWrapper()
  196. {
  197. return sGlobalRunnableClassUserWrapper;
  198. }
  199. void EA::Thread::Thread::SetGlobalRunnableClassUserWrapper(EA::Thread::RunnableClassUserWrapper pUserWrapper)
  200. {
  201. if(sGlobalRunnableClassUserWrapper != NULL)
  202. {
  203. // Can only be set once.
  204. EAT_ASSERT(false);
  205. }
  206. else
  207. sGlobalRunnableClassUserWrapper = pUserWrapper;
  208. }
  209. // Helper that selects a target processor based on the provided ThreadParameters structure and the various
  210. // pieces of shared state that EAThread maintains to implement a 'round-robin' style processor selection.
  211. int SelectProcessor(const EA::Thread::ThreadParameters* pTP, EA::Thread::AtomicInt32& sDefaultProcessor, EA::Thread::AtomicUint64& sDefaultProcessorMask)
  212. {
  213. int nProcessor;
  214. if (pTP && (pTP->mnProcessor >= 0))
  215. {
  216. nProcessor = pTP->mnProcessor;
  217. // This is a small attempt to try to spread out threads between processors. We don't
  218. // care much if another thread happens to be created here and races with this.
  219. if (nProcessor == EA::Thread::nLastProcessor)
  220. ++EA::Thread::nLastProcessor;
  221. }
  222. else
  223. {
  224. #if defined(EA_PLATFORM_MICROSOFT)
  225. if (!pTP || pTP->mnProcessor == EA::Thread::kProcessorAny)
  226. {
  227. // If the processor is not specified, then allow the scheduler to
  228. // run the thread on any available processor
  229. nProcessor = EA::Thread::kProcessorDefault;
  230. }
  231. else
  232. #endif
  233. if (sDefaultProcessor >= 0) // If the user has identified a specific processor...
  234. nProcessor = sDefaultProcessor;
  235. else if(sDefaultProcessor == EA::Thread::kProcessorDefault) // If the user explicitly asked for the default processor
  236. nProcessor = sDefaultProcessor;
  237. else
  238. {
  239. // NOTE(rparolin): The reason we have this round-robin code is that the
  240. // originally we used it on Xenon OS which required us to pick a CPU to run on.
  241. // After the Xenon was deprecated this code remained and is now a functional
  242. // requirement. We should probably deprecate and remove in the future but
  243. // currently teams are dependent on it.
  244. const uint64_t processorMask = sDefaultProcessorMask.GetValue();
  245. do
  246. {
  247. nProcessor = EA::Thread::nLastProcessor.Increment();
  248. if (nProcessor == MAXIMUM_PROCESSORS)
  249. {
  250. EA::Thread::nLastProcessor.SetValueConditional(0, MAXIMUM_PROCESSORS);
  251. nProcessor = 0;
  252. }
  253. } while ((((uint64_t)1 << nProcessor) & processorMask) == 0);
  254. }
  255. }
  256. return nProcessor;
  257. }
  258. EA::Thread::Thread::Thread()
  259. {
  260. mThreadData.mpData = NULL;
  261. }
  262. EA::Thread::Thread::Thread(const Thread& t)
  263. : mThreadData(t.mThreadData)
  264. {
  265. if(mThreadData.mpData)
  266. mThreadData.mpData->AddRef();
  267. }
  268. EA::Thread::Thread& EA::Thread::Thread::operator=(const Thread& t)
  269. {
  270. // We don't synchronize access to mpData; we assume that the user
  271. // synchronizes it or this Thread instances is used from a single thread.
  272. if(t.mThreadData.mpData)
  273. t.mThreadData.mpData->AddRef();
  274. if(mThreadData.mpData)
  275. mThreadData.mpData->Release();
  276. mThreadData = t.mThreadData;
  277. return *this;
  278. }
  279. EA::Thread::Thread::~Thread()
  280. {
  281. // We don't synchronize access to mpData; we assume that the user
  282. // synchronizes it or this Thread instances is used from a single thread.
  283. if(mThreadData.mpData)
  284. mThreadData.mpData->Release();
  285. }
  286. #if defined(EA_PLATFORM_XBOXONE)
  287. static DWORD WINAPI RunnableFunctionInternal(void* pContext)
  288. #else
  289. static unsigned int __stdcall RunnableFunctionInternal(void* pContext)
  290. #endif
  291. {
  292. // The parent thread is sharing memory with us and we need to
  293. // make sure our view of it is synchronized with the parent.
  294. EAReadWriteBarrier();
  295. EAThreadDynamicData* const pTDD = (EAThreadDynamicData*)pContext;
  296. EA::Thread::RunnableFunction pFunction = (EA::Thread::RunnableFunction)pTDD->mpStartContext[0];
  297. void* pCallContext = pTDD->mpStartContext[1];
  298. EA::Thread::SetCurrentThreadHandle(pTDD->mpStartContext[2], false);
  299. pTDD->mpStackBase = EA::Thread::GetStackBase();
  300. pTDD->mnStatus = EA::Thread::Thread::kStatusRunning;
  301. EA::Thread::SetThreadName(pTDD->mhThread, pTDD->mName);
  302. if(pTDD->mpBeginThreadUserWrapper != NULL)
  303. {
  304. EA::Thread::RunnableFunctionUserWrapper pWrapperFunction = (EA::Thread::RunnableFunctionUserWrapper)pTDD->mpBeginThreadUserWrapper;
  305. // if user wrapper is specified, call user wrapper and pass down the pFunction and pContext
  306. pTDD->mnReturnValue = pWrapperFunction(pFunction, pCallContext);
  307. }
  308. else
  309. {
  310. pTDD->mnReturnValue = pFunction(pCallContext);
  311. }
  312. const unsigned int nReturnValue = (unsigned int)pTDD->mnReturnValue;
  313. EA::Thread::SetCurrentThreadHandle(0, false);
  314. pTDD->mnStatus = EA::Thread::Thread::kStatusEnded;
  315. pTDD->Release();
  316. return nReturnValue;
  317. }
  318. void EA::Thread::Thread::SetAffinityMask(EA::Thread::ThreadAffinityMask nAffinityMask)
  319. {
  320. if(mThreadData.mpData->mhThread)
  321. {
  322. EA::Thread::SetThreadAffinityMask(mThreadData.mpData->mhThread, nAffinityMask);
  323. }
  324. }
  325. EA::Thread::ThreadAffinityMask EA::Thread::Thread::GetAffinityMask()
  326. {
  327. if(mThreadData.mpData->mhThread)
  328. {
  329. return mThreadData.mpData->mnThreadAffinityMask;
  330. }
  331. return kThreadAffinityMaskAny;
  332. }
  333. EA::Thread::ThreadId EA::Thread::Thread::Begin(RunnableFunction pFunction, void* pContext, const ThreadParameters* pTP, RunnableFunctionUserWrapper pUserWrapper)
  334. {
  335. // Check there is an entry for the current thread context in our ThreadDynamicData array.
  336. ThreadId thisThreadId = GetThreadId();
  337. if(!FindThreadDynamicData(thisThreadId))
  338. {
  339. EAThreadDynamicData* pData = new(AllocateThreadDynamicData()) EAThreadDynamicData;
  340. if(pData)
  341. {
  342. pData->AddRef(); // AddRef for ourselves, to be released upon this Thread class being deleted or upon Begin being called again for a new thread.
  343. // Do no AddRef for thread execution because this is not an EAThread managed thread.
  344. pData->AddRef(); // AddRef for this function, to be released upon this function's exit.
  345. pData->mhThread = thisThreadId;
  346. pData->mnThreadId = GetCurrentThreadId();
  347. strncpy(pData->mName, "external", EATHREAD_NAME_SIZE);
  348. pData->mName[EATHREAD_NAME_SIZE - 1] = 0;
  349. pData->mpStackBase = EA::Thread::GetStackBase();
  350. }
  351. }
  352. if(mThreadData.mpData)
  353. mThreadData.mpData->Release(); // Matches the "AddRef for ourselves" below.
  354. // Win32-like platforms don't support user-supplied stacks. A user-supplied stack pointer
  355. // here would be a waste of user memory, and so we assert that mpStack == NULL.
  356. EAT_ASSERT(!pTP || (pTP->mpStack == NULL));
  357. // We use the pData temporary throughout this function because it's possible that mThreadData.mpData could be
  358. // modified as we are executing, in particular in the case that mThreadData.mpData is destroyed and changed
  359. // during execution.
  360. EAThreadDynamicData* pData = new(AllocateThreadDynamicData()) EAThreadDynamicData; // Note that we use a special new here which doesn't use the heap.
  361. mThreadData.mpData = pData;
  362. pData->AddRef(); // AddRef for ourselves, to be released upon this Thread class being deleted or upon Begin being called again for a new thread.
  363. pData->AddRef(); // AddRef for the thread, to be released upon the thread exiting.
  364. pData->AddRef(); // AddRef for this function, to be released upon this function's exit.
  365. pData->mhThread = kThreadIdInvalid;
  366. pData->mpStartContext[0] = pFunction;
  367. pData->mpStartContext[1] = pContext;
  368. pData->mpBeginThreadUserWrapper = pUserWrapper;
  369. pData->mnThreadAffinityMask = pTP ? pTP->mnAffinityMask : kThreadAffinityMaskAny;
  370. const unsigned nStackSize = pTP ? (unsigned)pTP->mnStackSize : 0;
  371. #if defined(EA_PLATFORM_XBOXONE)
  372. // Capilano no longer supports _beginthreadex. Using CreateThread instead may cause issues when using the MS CRT
  373. // according to MSDN (memory leaks or possibly crashes) as it does not initialize the CRT. This a reasonable
  374. // workaround while we wait for clarification from MS on what the recommended threading APIs are for Capilano.
  375. HANDLE hThread = CreateThread(NULL, nStackSize, RunnableFunctionInternal, pData, CREATE_SUSPENDED, reinterpret_cast<LPDWORD>(&pData->mnThreadId));
  376. #else
  377. HANDLE hThread = (HANDLE)_beginthreadex(NULL, nStackSize, RunnableFunctionInternal, pData, CREATE_SUSPENDED, &pData->mnThreadId);
  378. #endif
  379. if(hThread)
  380. {
  381. pData->mhThread = hThread;
  382. if(pTP)
  383. SetName(pTP->mpName);
  384. pData->mpStartContext[2] = hThread;
  385. if(pTP && (pTP->mnPriority != kThreadPriorityDefault))
  386. SetPriority(pTP->mnPriority);
  387. #if defined(EA_PLATFORM_WINDOWS) || defined(EA_PLATFORM_XBOXONE)
  388. if (pTP)
  389. {
  390. auto result = SetThreadPriorityBoost(pData->mhThread, pTP->mbDisablePriorityBoost);
  391. EAT_ASSERT(result != 0);
  392. EA_UNUSED(result);
  393. }
  394. #endif
  395. #if defined(EA_PLATFORM_MICROSOFT)
  396. int nProcessor = SelectProcessor(pTP, sDefaultProcessor, sDefaultProcessorMask);
  397. if(pTP && pTP->mnProcessor == EA::Thread::kProcessorAny)
  398. SetAffinityMask(pTP->mnAffinityMask);
  399. else
  400. SetProcessor(nProcessor);
  401. #endif
  402. ResumeThread(hThread);
  403. pData->Release(); // Matches AddRef for this function.
  404. return hThread;
  405. }
  406. pData->Release(); // Matches AddRef for this function.
  407. pData->Release(); // Matches AddRef for this Thread class above.
  408. pData->Release(); // Matches AddRef for the thread above.
  409. mThreadData.mpData = NULL; // mThreadData.mpData == pData
  410. return (ThreadId)kThreadIdInvalid;
  411. }
  412. #if defined(EA_PLATFORM_XBOXONE)
  413. static DWORD WINAPI RunnableObjectInternal(void* pContext)
  414. #else
  415. static unsigned int __stdcall RunnableObjectInternal(void* pContext)
  416. #endif
  417. {
  418. // The parent thread is sharing memory with us and we need to
  419. // make sure our view of it is synchronized with the parent.
  420. EAReadWriteBarrier();
  421. EAThreadDynamicData* const pTDD = (EAThreadDynamicData*)pContext;
  422. EA::Thread::IRunnable* pRunnable = (EA::Thread::IRunnable*)pTDD->mpStartContext[0];
  423. void* pCallContext = pTDD->mpStartContext[1];
  424. EA::Thread::SetCurrentThreadHandle(pTDD->mpStartContext[2], false);
  425. pTDD->mnStatus = EA::Thread::Thread::kStatusRunning;
  426. EA::Thread::SetThreadName(pTDD->mhThread, pTDD->mName);
  427. if(pTDD->mpBeginThreadUserWrapper)
  428. {
  429. EA::Thread::RunnableClassUserWrapper pWrapperClass = (EA::Thread::RunnableClassUserWrapper)pTDD->mpBeginThreadUserWrapper;
  430. // if user wrapper is specified, call user wrapper and pass down the pFunction and pContext
  431. pTDD->mnReturnValue = pWrapperClass(pRunnable, pCallContext);
  432. }
  433. else
  434. pTDD->mnReturnValue = pRunnable->Run(pCallContext);
  435. const unsigned int nReturnValue = (unsigned int)pTDD->mnReturnValue;
  436. EA::Thread::SetCurrentThreadHandle(0, false);
  437. pTDD->mnStatus = EA::Thread::Thread::kStatusEnded;
  438. pTDD->Release();
  439. return nReturnValue;
  440. }
  441. EA::Thread::ThreadId EA::Thread::Thread::Begin(IRunnable* pRunnable, void* pContext, const ThreadParameters* pTP, RunnableClassUserWrapper pUserWrapper)
  442. {
  443. if(mThreadData.mpData)
  444. mThreadData.mpData->Release(); // Matches the "AddRef for ourselves" below.
  445. // Win32-like platforms don't support user-supplied stacks. A user-supplied stack pointer
  446. // here would be a waste of user memory, and so we assert that mpStack == NULL.
  447. EAT_ASSERT(!pTP || (pTP->mpStack == NULL));
  448. // We use the pData temporary throughout this function because it's possible that mThreadData.mpData could be
  449. // modified as we are executing, in particular in the case that mThreadData.mpData is destroyed and changed
  450. // during execution.
  451. EAThreadDynamicData* pData = new(AllocateThreadDynamicData()) EAThreadDynamicData; // Note that we use a special new here which doesn't use the heap.
  452. mThreadData.mpData = pData;
  453. pData->AddRef(); // AddRef for ourselves, to be released upon this Thread class being deleted or upon Begin being called again for a new thread.
  454. pData->AddRef(); // AddRef for the thread, to be released upon the thread exiting.
  455. pData->AddRef(); // AddRef for this function, to be released upon this function's exit.
  456. pData->mhThread = kThreadIdInvalid;
  457. pData->mpStartContext[0] = pRunnable;
  458. pData->mpStartContext[1] = pContext;
  459. pData->mpBeginThreadUserWrapper = pUserWrapper;
  460. pData->mnThreadAffinityMask = pTP ? pTP->mnAffinityMask : kThreadAffinityMaskAny;
  461. const unsigned nStackSize = pTP ? (unsigned)pTP->mnStackSize : 0;
  462. #if defined(EA_PLATFORM_XBOXONE)
  463. // Capilano no longer supports _beginthreadex. Using CreateThread instead may cause issues when using the MS CRT
  464. // according to MSDN (memory leaks or possibly crashes) as it does not initialize the CRT. This a reasonable
  465. // workaround while we wait for clarification from MS on what the recommended threading APIs are for Capilano.
  466. HANDLE hThread = CreateThread(NULL, nStackSize, RunnableObjectInternal, pData, CREATE_SUSPENDED, reinterpret_cast<LPDWORD>(&pData->mnThreadId));
  467. #else
  468. HANDLE hThread = (HANDLE)_beginthreadex(NULL, nStackSize, RunnableObjectInternal, pData, CREATE_SUSPENDED, &pData->mnThreadId);
  469. #endif
  470. if(hThread)
  471. {
  472. pData->mhThread = hThread;
  473. if(pTP)
  474. SetName(pTP->mpName);
  475. pData->mpStartContext[2] = hThread;
  476. if(pTP && (pTP->mnPriority != kThreadPriorityDefault))
  477. SetPriority(pTP->mnPriority);
  478. #if defined(EA_PLATFORM_WINDOWS) || defined(EA_PLATFORM_XBOXONE)
  479. if (pTP)
  480. {
  481. auto result = SetThreadPriorityBoost(pData->mhThread, pTP->mbDisablePriorityBoost);
  482. EAT_ASSERT(result != 0);
  483. EA_UNUSED(result);
  484. }
  485. #endif
  486. #if defined(EA_PLATFORM_MICROSOFT)
  487. int nProcessor = SelectProcessor(pTP, sDefaultProcessor, sDefaultProcessorMask);
  488. if(pTP && pTP->mnProcessor == EA::Thread::kProcessorAny)
  489. SetAffinityMask(pTP->mnAffinityMask);
  490. else
  491. SetProcessor(nProcessor);
  492. #endif
  493. ResumeThread(hThread); // This will unsuspend the thread.
  494. pData->Release(); // Matches AddRef for this function.
  495. return hThread;
  496. }
  497. pData->Release(); // Matches AddRef for this function.
  498. pData->Release(); // Matches AddRef for this Thread class above.
  499. pData->Release(); // Matches AddRef for the thread above.
  500. mThreadData.mpData = NULL;
  501. return (ThreadId)kThreadIdInvalid;
  502. }
  503. EA::Thread::Thread::Status EA::Thread::Thread::WaitForEnd(const ThreadTime& timeoutAbsolute, intptr_t* pThreadReturnValue)
  504. {
  505. // The mThreadData memory is shared between threads and when
  506. // reading it we must be synchronized.
  507. EAReadWriteBarrier();
  508. // A mutex lock around mpData is not needed below because
  509. // mpData is never allowed to go from non-NULL to NULL.
  510. // Todo: Consider that there may be a subtle race condition here if
  511. // the user immediately calls WaitForEnd right after calling Begin.
  512. if(mThreadData.mpData)
  513. {
  514. if(mThreadData.mpData->mhThread) // If it was started...
  515. {
  516. // We must not call WaitForEnd from the thread we are waiting to end. That would result in a deadlock.
  517. EAT_ASSERT(mThreadData.mpData->mhThread != EA::Thread::GetThreadId());
  518. // dwResult normally should be 'WAIT_OBJECT_0', but can also be WAIT_ABANDONED or WAIT_FAILED.
  519. const DWORD dwResult = ::WaitForSingleObject(mThreadData.mpData->mhThread, RelativeTimeoutFromAbsoluteTimeout(timeoutAbsolute));
  520. if(dwResult == WAIT_TIMEOUT)
  521. return kStatusRunning;
  522. // Close the handle now so as to minimize handle proliferation.
  523. ::CloseHandle(mThreadData.mpData->mhThread);
  524. mThreadData.mpData->mhThread = 0;
  525. mThreadData.mpData->mnStatus = kStatusEnded;
  526. }
  527. if(pThreadReturnValue)
  528. {
  529. EAReadWriteBarrier();
  530. *pThreadReturnValue = mThreadData.mpData->mnReturnValue;
  531. }
  532. return kStatusEnded; // A thread was created, so it must have ended.
  533. }
  534. else
  535. {
  536. // Else the user hasn't started the thread yet, so we wait until the user starts it.
  537. // Ideally, what we really want to do here is wait for some kind of signal.
  538. // Instead for the time being we do a polling loop.
  539. while((!mThreadData.mpData || !mThreadData.mpData->mhThread) && (GetThreadTime() < timeoutAbsolute))
  540. {
  541. ThreadSleep(1);
  542. EAReadWriteBarrier();
  543. EACompilerMemoryBarrier();
  544. }
  545. if(mThreadData.mpData)
  546. return WaitForEnd(timeoutAbsolute);
  547. }
  548. return kStatusNone; // No thread has been started.
  549. }
  550. EA::Thread::Thread::Status EA::Thread::Thread::GetStatus(intptr_t* pThreadReturnValue) const
  551. {
  552. // The mThreadData memory is shared between threads and when
  553. // reading it we must be synchronized.
  554. EAReadWriteBarrier();
  555. // A mutex lock around mpData is not needed below because
  556. // mpData is never allowed to go from non-NULL to NULL.
  557. if(mThreadData.mpData)
  558. {
  559. if(mThreadData.mpData->mhThread) // If the thread has been started...
  560. {
  561. DWORD dwExitStatus;
  562. // Note that GetExitCodeThread is a hazard if the user of a thread exits
  563. // with a return value that is equal to the value of STILL_ACTIVE (i.e. 259).
  564. // We can document that users shouldn't do this, or we can change the code
  565. // here to use WaitForSingleObject(hThread, 0) and assume the thread is
  566. // still active if the return value is WAIT_TIMEOUT.
  567. if(::GetExitCodeThread(mThreadData.mpData->mhThread, &dwExitStatus))
  568. {
  569. if(dwExitStatus == STILL_ACTIVE)
  570. return kStatusRunning; // Nothing has changed.
  571. ::CloseHandle(mThreadData.mpData->mhThread); // Do this now so as to minimize handle proliferation.
  572. mThreadData.mpData->mhThread = 0;
  573. } // else fall through.
  574. } // else fall through.
  575. if(pThreadReturnValue)
  576. *pThreadReturnValue = mThreadData.mpData->mnReturnValue;
  577. mThreadData.mpData->mnStatus = kStatusEnded;
  578. return kStatusEnded;
  579. }
  580. return kStatusNone;
  581. }
  582. EA::Thread::ThreadId EA::Thread::Thread::GetId() const
  583. {
  584. // A mutex lock around mpData is not needed below because
  585. // mpData is never allowed to go from non-NULL to NULL.
  586. if(mThreadData.mpData)
  587. return (ThreadId)mThreadData.mpData->mhThread;
  588. return kThreadIdInvalid;
  589. }
  590. int EA::Thread::Thread::GetPriority() const
  591. {
  592. // A mutex lock around mpData is not needed below because
  593. // mpData is never allowed to go from non-NULL to NULL.
  594. if(mThreadData.mpData)
  595. {
  596. const int nPriority = ::GetThreadPriority(mThreadData.mpData->mhThread);
  597. return kThreadPriorityDefault + (nPriority - THREAD_PRIORITY_NORMAL);
  598. }
  599. return kThreadPriorityUnknown;
  600. }
  601. bool EA::Thread::Thread::SetPriority(int nPriority)
  602. {
  603. // A mutex lock around mpData is not needed below because
  604. // mpData is never allowed to go from non-NULL to NULL.
  605. // For more information on how Windows handle thread priority based on process priority, see
  606. // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/scheduling_priorities.asp
  607. EAT_ASSERT(nPriority != kThreadPriorityUnknown);
  608. if(mThreadData.mpData)
  609. {
  610. int nNewPriority = THREAD_PRIORITY_NORMAL + (nPriority - kThreadPriorityDefault);
  611. bool result = ::SetThreadPriority(mThreadData.mpData->mhThread, nNewPriority) != 0;
  612. // Windows process running in NORMAL_PRIORITY_CLASS is picky about the priority passed in.
  613. // So we need to set the priority to the next priority supported
  614. #if defined(EA_PLATFORM_WINDOWS) || defined(EA_PLATFORM_XBOXONE)
  615. while(!result)
  616. {
  617. if(nNewPriority >= THREAD_PRIORITY_TIME_CRITICAL)
  618. return ::SetThreadPriority(mThreadData.mpData->mhThread, THREAD_PRIORITY_TIME_CRITICAL) != 0;
  619. if(nNewPriority <= THREAD_PRIORITY_IDLE)
  620. return ::SetThreadPriority(mThreadData.mpData->mhThread, THREAD_PRIORITY_IDLE) != 0;
  621. result = ::SetThreadPriority(mThreadData.mpData->mhThread, nNewPriority) != 0;
  622. nNewPriority++;
  623. }
  624. #endif
  625. return result;
  626. }
  627. return false;
  628. }
  629. void EA::Thread::Thread::SetProcessor(int nProcessor)
  630. {
  631. if(mThreadData.mpData)
  632. {
  633. #if defined(EA_PLATFORM_XBOXONE)
  634. static int nProcessorCount = GetProcessorCount();
  635. if(nProcessor >= nProcessorCount)
  636. nProcessor %= nProcessorCount;
  637. ThreadAffinityMask mask = 0x7F; // default to all 7 available cores.
  638. if (nProcessor >= 0)
  639. mask = ((ThreadAffinityMask)1) << nProcessor;
  640. SetThreadAffinityMask(mThreadData.mpData->mhThread, mask);
  641. #else
  642. static int nProcessorCount = GetProcessorCount();
  643. if(nProcessor < 0)
  644. nProcessor = MAXIMUM_PROCESSORS; // This causes the SetThreadIdealProcessor to reset to 'no ideal processor'.
  645. else
  646. {
  647. if(nProcessor >= nProcessorCount)
  648. nProcessor %= nProcessorCount;
  649. }
  650. // SetThreadIdealProcessor differs from SetThreadAffinityMask in that SetThreadIdealProcessor is not
  651. // a strict assignment, and it allows the OS to move the thread if the ideal processor is busy.
  652. // SetThreadAffinityMask is a more rigid assignment, but it can result in slower performance and
  653. // possibly hangs due to processor contention between threads. For Windows we use SetIdealThreadProcessor
  654. // in the name of safety and likely better overall performance.
  655. SetThreadIdealProcessor(mThreadData.mpData->mhThread, (DWORD)nProcessor);
  656. #endif
  657. }
  658. }
  659. typedef VOID (APIENTRY *PAPCFUNC)(_In_ ULONG_PTR dwParam);
  660. extern "C" WINBASEAPI DWORD WINAPI QueueUserAPC(_In_ PAPCFUNC pfnAPC, _In_ HANDLE hThread, _In_ ULONG_PTR dwData);
  661. void EA::Thread::Thread::Wake()
  662. {
  663. // A mutex lock around mpData is not needed below because
  664. // mpData is never allowed to go from non-NULL to NULL.
  665. struct ThreadWake{ static void WINAPI Empty(ULONG_PTR){} };
  666. if(mThreadData.mpData && mThreadData.mpData->mhThread)
  667. ::QueueUserAPC((PAPCFUNC)ThreadWake::Empty, mThreadData.mpData->mhThread, 0);
  668. }
  669. const char* EA::Thread::Thread::GetName() const
  670. {
  671. if(mThreadData.mpData)
  672. return mThreadData.mpData->mName;
  673. return "";
  674. }
  675. void EA::Thread::Thread::SetName(const char* pName)
  676. {
  677. if (mThreadData.mpData && pName)
  678. EA::Thread::Internal::SetThreadName(mThreadData.mpData, pName);
  679. }
  680. #ifdef WARNING_INIT_SEG_PUSHED
  681. #undef WARNING_INIT_SEG_PUSHED
  682. EA_RESTORE_VC_WARNING() // 4073 4075
  683. #endif
  684. #endif // EA_PLATFORM_MICROSOFT
  685. EA_RESTORE_VC_WARNING() // 6312 6322
  686. #if defined(EA_COMPILER_MSVC) && EA_COMPILER_VERSION >= 1900 // VS2015+
  687. EA_RESTORE_VC_WARNING() // 5031 5032
  688. // #pragma warning(pop): likely mismatch, popping warning state pushed in different file / detected #pragma warning(push) with no corresponding
  689. #endif