eathread_thread_pc.cpp 29 KB

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