OVR_ThreadsWinAPI.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. /************************************************************************************
  2. Filename : OVR_ThreadsWinAPI.cpp
  3. Platform : WinAPI
  4. Content : Windows specific thread-related (safe) functionality
  5. Created : September 19, 2012
  6. Notes :
  7. Copyright : Copyright 2014 Oculus VR, LLC All Rights reserved.
  8. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
  9. you may not use the Oculus VR Rift SDK except in compliance with the License,
  10. which is provided at the time of installation or download, or which
  11. otherwise accompanies this software in either electronic or hard copy form.
  12. You may obtain a copy of the License at
  13. http://www.oculusvr.com/licenses/LICENSE-3.2
  14. Unless required by applicable law or agreed to in writing, the Oculus VR SDK
  15. distributed under the License is distributed on an "AS IS" BASIS,
  16. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. See the License for the specific language governing permissions and
  18. limitations under the License.
  19. ************************************************************************************/
  20. #include "OVR_Threads.h"
  21. #include "OVR_Hash.h"
  22. #include "OVR_Log.h"
  23. #include "OVR_Timer.h"
  24. #ifdef OVR_ENABLE_THREADS
  25. // For _beginthreadex / _endtheadex
  26. #include <process.h>
  27. namespace OVR {
  28. //-----------------------------------------------------------------------------------
  29. // *** Internal Mutex implementation class
  30. class MutexImpl : public NewOverrideBase
  31. {
  32. // System mutex or semaphore
  33. HANDLE hMutexOrSemaphore;
  34. bool Recursive;
  35. volatile unsigned LockCount;
  36. friend class WaitConditionImpl;
  37. public:
  38. // Constructor/destructor
  39. MutexImpl(bool recursive = 1);
  40. ~MutexImpl();
  41. // Locking functions
  42. void DoLock();
  43. bool TryLock();
  44. void Unlock(Mutex* pmutex);
  45. // Returns 1 if the mutes is currently locked
  46. bool IsLockedByAnotherThread(Mutex* pmutex);
  47. };
  48. // *** Constructor/destructor
  49. MutexImpl::MutexImpl(bool recursive)
  50. {
  51. Recursive = recursive;
  52. LockCount = 0;
  53. #if defined(OVR_OS_WIN32) // Older versions of Windows don't support CreateSemaphoreEx, so stick with CreateSemaphore for portability.
  54. hMutexOrSemaphore = Recursive ? CreateMutex(NULL, 0, NULL) : CreateSemaphore(NULL, 1, 1, NULL);
  55. #else
  56. // No CreateSemaphore() call, so emulate it.
  57. hMutexOrSemaphore = Recursive ? CreateMutex(NULL, 0, NULL) : CreateSemaphoreEx(NULL, 1, 1, NULL, 0, SEMAPHORE_ALL_ACCESS);
  58. #endif
  59. }
  60. MutexImpl::~MutexImpl()
  61. {
  62. CloseHandle(hMutexOrSemaphore);
  63. }
  64. // Lock and try lock
  65. void MutexImpl::DoLock()
  66. {
  67. if (::WaitForSingleObject(hMutexOrSemaphore, INFINITE) != WAIT_OBJECT_0)
  68. return;
  69. LockCount++;
  70. }
  71. bool MutexImpl::TryLock()
  72. {
  73. DWORD ret;
  74. if ((ret=::WaitForSingleObject(hMutexOrSemaphore, 0)) != WAIT_OBJECT_0)
  75. return 0;
  76. LockCount++;
  77. return 1;
  78. }
  79. void MutexImpl::Unlock(Mutex* pmutex)
  80. {
  81. OVR_UNUSED(pmutex);
  82. unsigned lockCount;
  83. LockCount--;
  84. lockCount = LockCount;
  85. // Release mutex
  86. if ((Recursive ? ReleaseMutex(hMutexOrSemaphore) :
  87. ReleaseSemaphore(hMutexOrSemaphore, 1, NULL)) != 0)
  88. {
  89. // This used to call Wait handlers if lockCount == 0.
  90. }
  91. }
  92. bool MutexImpl::IsLockedByAnotherThread(Mutex* pmutex)
  93. {
  94. // There could be multiple interpretations of IsLocked with respect to current thread
  95. if (LockCount == 0)
  96. return 0;
  97. if (!TryLock())
  98. return 1;
  99. Unlock(pmutex);
  100. return 0;
  101. }
  102. /*
  103. bool MutexImpl::IsSignaled() const
  104. {
  105. // An mutex is signaled if it is not locked ANYWHERE
  106. // Note that this is different from IsLockedByAnotherThread function,
  107. // that takes current thread into account
  108. return LockCount == 0;
  109. }
  110. */
  111. // *** Actual Mutex class implementation
  112. Mutex::Mutex(bool recursive)
  113. {
  114. pImpl = new MutexImpl(recursive);
  115. }
  116. Mutex::~Mutex()
  117. {
  118. delete pImpl;
  119. }
  120. // Lock and try lock
  121. void Mutex::DoLock()
  122. {
  123. pImpl->DoLock();
  124. }
  125. bool Mutex::TryLock()
  126. {
  127. return pImpl->TryLock();
  128. }
  129. void Mutex::Unlock()
  130. {
  131. pImpl->Unlock(this);
  132. }
  133. bool Mutex::IsLockedByAnotherThread()
  134. {
  135. return pImpl->IsLockedByAnotherThread(this);
  136. }
  137. //-----------------------------------------------------------------------------------
  138. // ***** Event
  139. bool Event::Wait(unsigned delay)
  140. {
  141. Mutex::Locker lock(&StateMutex);
  142. // Do the correct amount of waiting
  143. if (delay == OVR_WAIT_INFINITE)
  144. {
  145. while(!State)
  146. StateWaitCondition.Wait(&StateMutex);
  147. }
  148. else if (delay)
  149. {
  150. if (!State)
  151. StateWaitCondition.Wait(&StateMutex, delay);
  152. }
  153. bool state = State;
  154. // Take care of temporary 'pulsing' of a state
  155. if (Temporary)
  156. {
  157. Temporary = false;
  158. State = false;
  159. }
  160. return state;
  161. }
  162. void Event::updateState(bool newState, bool newTemp, bool mustNotify)
  163. {
  164. Mutex::Locker lock(&StateMutex);
  165. State = newState;
  166. Temporary = newTemp;
  167. if (mustNotify)
  168. StateWaitCondition.NotifyAll();
  169. }
  170. //-----------------------------------------------------------------------------------
  171. // ***** Win32 Wait Condition Implementation
  172. // Internal implementation class
  173. class WaitConditionImpl : public NewOverrideBase
  174. {
  175. // Event pool entries for extra events
  176. struct EventPoolEntry : public NewOverrideBase
  177. {
  178. HANDLE hEvent;
  179. EventPoolEntry *pNext;
  180. EventPoolEntry *pPrev;
  181. };
  182. Lock WaitQueueLoc;
  183. // Stores free events that can be used later
  184. EventPoolEntry * pFreeEventList;
  185. // A queue of waiting objects to be signaled
  186. EventPoolEntry* pQueueHead;
  187. EventPoolEntry* pQueueTail;
  188. // Allocation functions for free events
  189. EventPoolEntry* GetNewEvent();
  190. void ReleaseEvent(EventPoolEntry* pevent);
  191. // Queue operations
  192. void QueuePush(EventPoolEntry* pentry);
  193. EventPoolEntry* QueuePop();
  194. void QueueFindAndRemove(EventPoolEntry* pentry);
  195. public:
  196. // Constructor/destructor
  197. WaitConditionImpl();
  198. ~WaitConditionImpl();
  199. // Release mutex and wait for condition. The mutex is re-acqured after the wait.
  200. bool Wait(Mutex *pmutex, unsigned delay = OVR_WAIT_INFINITE);
  201. // Notify a condition, releasing at one object waiting
  202. void Notify();
  203. // Notify a condition, releasing all objects waiting
  204. void NotifyAll();
  205. };
  206. WaitConditionImpl::WaitConditionImpl()
  207. {
  208. pFreeEventList = 0;
  209. pQueueHead =
  210. pQueueTail = 0;
  211. }
  212. WaitConditionImpl::~WaitConditionImpl()
  213. {
  214. // Free all the resources
  215. EventPoolEntry* p = pFreeEventList;
  216. EventPoolEntry* pentry;
  217. while(p)
  218. {
  219. // Move to next
  220. pentry = p;
  221. p = p->pNext;
  222. // Delete old
  223. ::CloseHandle(pentry->hEvent);
  224. delete pentry;
  225. }
  226. // Shouldn't we also consider the queue?
  227. // To be safe
  228. pFreeEventList = 0;
  229. pQueueHead =
  230. pQueueTail = 0;
  231. }
  232. // Allocation functions for free events
  233. WaitConditionImpl::EventPoolEntry* WaitConditionImpl::GetNewEvent()
  234. {
  235. EventPoolEntry* pentry;
  236. // If there are any free nodes, use them
  237. if (pFreeEventList)
  238. {
  239. pentry = pFreeEventList;
  240. pFreeEventList = pFreeEventList->pNext;
  241. }
  242. else
  243. {
  244. // Allocate a new node
  245. pentry = new EventPoolEntry;
  246. pentry->pNext = 0;
  247. pentry->pPrev = 0;
  248. // Non-signaled manual event
  249. pentry->hEvent = ::CreateEvent(NULL, TRUE, 0, NULL);
  250. }
  251. return pentry;
  252. }
  253. void WaitConditionImpl::ReleaseEvent(EventPoolEntry* pevent)
  254. {
  255. // Mark event as non-signaled
  256. ::ResetEvent(pevent->hEvent);
  257. // And add it to free pool
  258. pevent->pNext = pFreeEventList;
  259. pevent->pPrev = 0;
  260. pFreeEventList = pevent;
  261. }
  262. // Queue operations
  263. void WaitConditionImpl::QueuePush(EventPoolEntry* pentry)
  264. {
  265. // Items already exist? Just add to tail
  266. if (pQueueTail)
  267. {
  268. pentry->pPrev = pQueueTail;
  269. pQueueTail->pNext = pentry;
  270. pentry->pNext = 0;
  271. pQueueTail = pentry;
  272. }
  273. else
  274. {
  275. // No items in queue
  276. pentry->pNext =
  277. pentry->pPrev = 0;
  278. pQueueHead =
  279. pQueueTail = pentry;
  280. }
  281. }
  282. WaitConditionImpl::EventPoolEntry* WaitConditionImpl::QueuePop()
  283. {
  284. EventPoolEntry* pentry = pQueueHead;
  285. // No items, null pointer
  286. if (pentry)
  287. {
  288. // More items after this one? just grab the first item
  289. if (pQueueHead->pNext)
  290. {
  291. pQueueHead = pentry->pNext;
  292. pQueueHead->pPrev = 0;
  293. }
  294. else
  295. {
  296. // Last item left
  297. pQueueTail =
  298. pQueueHead = 0;
  299. }
  300. }
  301. return pentry;
  302. }
  303. void WaitConditionImpl::QueueFindAndRemove(EventPoolEntry* pentry)
  304. {
  305. // Do an exhaustive search looking for an entry
  306. EventPoolEntry* p = pQueueHead;
  307. while(p)
  308. {
  309. // Entry found? Remove.
  310. if (p == pentry)
  311. {
  312. // Remove the node form the list
  313. // Prev link
  314. if (pentry->pPrev)
  315. pentry->pPrev->pNext = pentry->pNext;
  316. else
  317. pQueueHead = pentry->pNext;
  318. // Next link
  319. if (pentry->pNext)
  320. pentry->pNext->pPrev = pentry->pPrev;
  321. else
  322. pQueueTail = pentry->pPrev;
  323. // Done
  324. return;
  325. }
  326. // Move to next item
  327. p = p->pNext;
  328. }
  329. }
  330. bool WaitConditionImpl::Wait(Mutex *pmutex, unsigned delay)
  331. {
  332. bool result = 0;
  333. unsigned i;
  334. unsigned lockCount = pmutex->pImpl->LockCount;
  335. EventPoolEntry* pentry;
  336. // Mutex must have been locked
  337. if (lockCount == 0)
  338. return 0;
  339. // Add an object to the wait queue
  340. WaitQueueLoc.DoLock();
  341. QueuePush(pentry = GetNewEvent());
  342. WaitQueueLoc.Unlock();
  343. // Finally, release a mutex or semaphore
  344. if (pmutex->pImpl->Recursive)
  345. {
  346. // Release the recursive mutex N times
  347. pmutex->pImpl->LockCount = 0;
  348. for(i=0; i<lockCount; i++)
  349. ::ReleaseMutex(pmutex->pImpl->hMutexOrSemaphore);
  350. }
  351. else
  352. {
  353. pmutex->pImpl->LockCount = 0;
  354. ::ReleaseSemaphore(pmutex->pImpl->hMutexOrSemaphore, 1, NULL);
  355. }
  356. // Note that there is a gap here between mutex.Unlock() and Wait(). However,
  357. // if notify() comes in at this point in the other thread it will set our
  358. // corresponding event so wait will just fall through, as expected.
  359. // Block and wait on the event
  360. DWORD waitResult = ::WaitForSingleObject(pentry->hEvent,
  361. (delay == OVR_WAIT_INFINITE) ? INFINITE : delay);
  362. /*
  363. repeat_wait:
  364. DWORD waitResult =
  365. ::MsgWaitForMultipleObjects(1, &pentry->hEvent, FALSE,
  366. (delay == OVR_WAIT_INFINITE) ? INFINITE : delay,
  367. QS_ALLINPUT);
  368. */
  369. WaitQueueLoc.DoLock();
  370. switch(waitResult)
  371. {
  372. case WAIT_ABANDONED:
  373. case WAIT_OBJECT_0:
  374. result = 1;
  375. // Wait was successful, therefore the event entry should already be removed
  376. // So just add entry back to a free list
  377. ReleaseEvent(pentry);
  378. break;
  379. /*
  380. case WAIT_OBJECT_0 + 1:
  381. // Messages in WINDOWS queue
  382. {
  383. MSG msg;
  384. PeekMessage(&msg, NULL, 0U, 0U, PM_NOREMOVE);
  385. WaitQueueLoc.Unlock();
  386. goto repeat_wait;
  387. }
  388. break; */
  389. default:
  390. // Timeout, our entry should still be in a queue
  391. QueueFindAndRemove(pentry);
  392. ReleaseEvent(pentry);
  393. }
  394. WaitQueueLoc.Unlock();
  395. // Re-aquire the mutex
  396. for(i=0; i<lockCount; i++)
  397. pmutex->DoLock();
  398. // Return the result
  399. return result;
  400. }
  401. // Notify a condition, releasing the least object in a queue
  402. void WaitConditionImpl::Notify()
  403. {
  404. Lock::Locker lock(&WaitQueueLoc);
  405. // Pop last entry & signal it
  406. EventPoolEntry* pentry = QueuePop();
  407. if (pentry)
  408. ::SetEvent(pentry->hEvent);
  409. }
  410. // Notify a condition, releasing all objects waiting
  411. void WaitConditionImpl::NotifyAll()
  412. {
  413. Lock::Locker lock(&WaitQueueLoc);
  414. // Pop and signal all events
  415. // NOTE : There is no need to release the events, it's the waiters job to do so
  416. EventPoolEntry* pentry = QueuePop();
  417. while (pentry)
  418. {
  419. ::SetEvent(pentry->hEvent);
  420. pentry = QueuePop();
  421. }
  422. }
  423. // *** Actual implementation of WaitCondition
  424. WaitCondition::WaitCondition()
  425. {
  426. pImpl = new WaitConditionImpl;
  427. }
  428. WaitCondition::~WaitCondition()
  429. {
  430. delete pImpl;
  431. }
  432. // Wait without a mutex
  433. bool WaitCondition::Wait(Mutex *pmutex, unsigned delay)
  434. {
  435. return pImpl->Wait(pmutex, delay);
  436. }
  437. // Notification
  438. void WaitCondition::Notify()
  439. {
  440. pImpl->Notify();
  441. }
  442. void WaitCondition::NotifyAll()
  443. {
  444. pImpl->NotifyAll();
  445. }
  446. //-----------------------------------------------------------------------------------
  447. // ***** Thread Class
  448. // Per-thread variable
  449. // MA: Don't use TLS for now - portability issues with DLLs, etc.
  450. /*
  451. #if !defined(OVR_CC_MSVC) || (OVR_CC_MSVC < 1300)
  452. __declspec(thread) Thread* pCurrentThread = 0;
  453. #else
  454. #pragma data_seg(".tls$")
  455. __declspec(thread) Thread* pCurrentThread = 0;
  456. #pragma data_seg(".rwdata")
  457. #endif
  458. */
  459. // *** Thread constructors.
  460. Thread::Thread(size_t stackSize, int processor)
  461. {
  462. CreateParams params;
  463. params.stackSize = stackSize;
  464. params.processor = processor;
  465. Init(params);
  466. }
  467. Thread::Thread(Thread::ThreadFn threadFunction, void* userHandle, size_t stackSize,
  468. int processor, Thread::ThreadState initialState)
  469. {
  470. CreateParams params(threadFunction, userHandle, stackSize, processor, initialState);
  471. Init(params);
  472. }
  473. Thread::Thread(const CreateParams& params)
  474. {
  475. Init(params);
  476. }
  477. void Thread::Init(const CreateParams& params)
  478. {
  479. // Clear the variables
  480. ThreadFlags = 0;
  481. ThreadHandle = 0;
  482. IdValue = 0;
  483. ExitCode = 0;
  484. SuspendCount = 0;
  485. StackSize = params.stackSize;
  486. Processor = params.processor;
  487. Priority = params.priority;
  488. // Clear Function pointers
  489. ThreadFunction = params.threadFunction;
  490. UserHandle = params.userHandle;
  491. if (params.initialState != NotRunning)
  492. Start(params.initialState);
  493. }
  494. Thread::~Thread()
  495. {
  496. // Thread should not running while object is being destroyed,
  497. // this would indicate ref-counting issue.
  498. //OVR_ASSERT(IsRunning() == 0);
  499. // Clean up thread.
  500. CleanupSystemThread();
  501. ThreadHandle = 0;
  502. }
  503. // *** Overridable User functions.
  504. // Default Run implementation
  505. int Thread::Run()
  506. {
  507. if (!ThreadFunction)
  508. return 0;
  509. int ret = ThreadFunction(this, UserHandle);
  510. return ret;
  511. }
  512. void Thread::OnExit()
  513. {
  514. }
  515. // Finishes the thread and releases internal reference to it.
  516. void Thread::FinishAndRelease()
  517. {
  518. // Note: thread must be US.
  519. ThreadFlags &= (uint32_t)~(OVR_THREAD_STARTED);
  520. ThreadFlags |= OVR_THREAD_FINISHED;
  521. // Release our reference; this is equivalent to 'delete this'
  522. // from the point of view of our thread.
  523. Release();
  524. }
  525. // *** ThreadList - used to tack all created threads
  526. class ThreadList : public NewOverrideBase
  527. {
  528. //------------------------------------------------------------------------
  529. struct ThreadHashOp
  530. {
  531. size_t operator()(const Thread* ptr)
  532. {
  533. return (((size_t)ptr) >> 6) ^ (size_t)ptr;
  534. }
  535. };
  536. HashSet<Thread*, ThreadHashOp> ThreadSet;
  537. Mutex ThreadMutex;
  538. WaitCondition ThreadsEmpty;
  539. // Track the root thread that created us.
  540. ThreadId RootThreadId;
  541. static ThreadList* volatile pRunningThreads;
  542. void addThread(Thread *pthread)
  543. {
  544. Mutex::Locker lock(&ThreadMutex);
  545. ThreadSet.Add(pthread);
  546. }
  547. void removeThread(Thread *pthread)
  548. {
  549. Mutex::Locker lock(&ThreadMutex);
  550. ThreadSet.Remove(pthread);
  551. if (ThreadSet.GetSize() == 0)
  552. ThreadsEmpty.Notify();
  553. }
  554. void finishAllThreads()
  555. {
  556. // Only original root thread can call this.
  557. OVR_ASSERT(GetCurrentThreadId() == RootThreadId);
  558. Mutex::Locker lock(&ThreadMutex);
  559. while (ThreadSet.GetSize() != 0)
  560. ThreadsEmpty.Wait(&ThreadMutex);
  561. }
  562. public:
  563. ThreadList()
  564. {
  565. RootThreadId = GetCurrentThreadId();
  566. }
  567. ~ThreadList() { }
  568. static void AddRunningThread(Thread *pthread)
  569. {
  570. // Non-atomic creation ok since only the root thread
  571. if (!pRunningThreads)
  572. {
  573. pRunningThreads = new ThreadList;
  574. OVR_ASSERT(pRunningThreads);
  575. }
  576. pRunningThreads->addThread(pthread);
  577. }
  578. // NOTE: 'pthread' might be a dead pointer when this is
  579. // called so it should not be accessed; it is only used
  580. // for removal.
  581. static void RemoveRunningThread(Thread *pthread)
  582. {
  583. OVR_ASSERT(pRunningThreads);
  584. pRunningThreads->removeThread(pthread);
  585. }
  586. static void FinishAllThreads()
  587. {
  588. // This is ok because only root thread can wait for other thread finish.
  589. if (pRunningThreads)
  590. {
  591. pRunningThreads->finishAllThreads();
  592. delete pRunningThreads;
  593. pRunningThreads = 0;
  594. }
  595. }
  596. };
  597. // By default, we have no thread list.
  598. ThreadList* volatile ThreadList::pRunningThreads = 0;
  599. // FinishAllThreads - exposed publicly in Thread.
  600. void Thread::FinishAllThreads()
  601. {
  602. ThreadList::FinishAllThreads();
  603. }
  604. // *** Run override
  605. int Thread::PRun()
  606. {
  607. // Suspend us on start, if requested
  608. if (ThreadFlags & OVR_THREAD_START_SUSPENDED)
  609. {
  610. Suspend();
  611. ThreadFlags &= (uint32_t)~OVR_THREAD_START_SUSPENDED;
  612. }
  613. // Call the virtual run function
  614. ExitCode = Run();
  615. return ExitCode;
  616. }
  617. /* MA: Don't use TLS for now.
  618. // Static function to return a pointer to the current thread
  619. void Thread::InitCurrentThread(Thread *pthread)
  620. {
  621. pCurrentThread = pthread;
  622. }
  623. // Static function to return a pointer to the current thread
  624. Thread* Thread::GetThread()
  625. {
  626. return pCurrentThread;
  627. }
  628. */
  629. // *** User overridables
  630. bool Thread::GetExitFlag() const
  631. {
  632. return (ThreadFlags & OVR_THREAD_EXIT) != 0;
  633. }
  634. void Thread::SetExitFlag(bool exitFlag)
  635. {
  636. // The below is atomic since ThreadFlags is AtomicInt.
  637. if (exitFlag)
  638. ThreadFlags |= OVR_THREAD_EXIT;
  639. else
  640. ThreadFlags &= (uint32_t) ~OVR_THREAD_EXIT;
  641. }
  642. // Determines whether the thread was running and is now finished
  643. bool Thread::IsFinished() const
  644. {
  645. return (ThreadFlags & OVR_THREAD_FINISHED) != 0;
  646. }
  647. // Determines whether the thread is suspended
  648. bool Thread::IsSuspended() const
  649. {
  650. return SuspendCount > 0;
  651. }
  652. // Returns current thread state
  653. Thread::ThreadState Thread::GetThreadState() const
  654. {
  655. if (IsSuspended())
  656. return Suspended;
  657. if (ThreadFlags & OVR_THREAD_STARTED)
  658. return Running;
  659. return NotRunning;
  660. }
  661. // Join thread
  662. bool Thread::Join(int maxWaitMs) const
  663. {
  664. // If polling,
  665. if (maxWaitMs == 0)
  666. {
  667. // Just return if finished
  668. return IsFinished();
  669. }
  670. // If waiting forever,
  671. else if (maxWaitMs > 0)
  672. {
  673. // Try waiting once
  674. WaitForSingleObject(ThreadHandle, maxWaitMs);
  675. // Return if the wait succeeded
  676. return IsFinished();
  677. }
  678. // While not finished,
  679. while (!IsFinished())
  680. {
  681. // Wait for the thread handle to signal
  682. WaitForSingleObject(ThreadHandle, INFINITE);
  683. }
  684. return true;
  685. }
  686. // ***** Thread management
  687. /* static */
  688. int Thread::GetOSPriority(ThreadPriority p)
  689. {
  690. switch(p)
  691. {
  692. // If the process is REALTIME_PRIORITY_CLASS then it could have priority values 3 through14 and -3 through -14.
  693. case Thread::CriticalPriority: return THREAD_PRIORITY_TIME_CRITICAL; // 15
  694. case Thread::HighestPriority: return THREAD_PRIORITY_HIGHEST; // 2
  695. case Thread::AboveNormalPriority: return THREAD_PRIORITY_ABOVE_NORMAL; // 1
  696. case Thread::NormalPriority: return THREAD_PRIORITY_NORMAL; // 0
  697. case Thread::BelowNormalPriority: return THREAD_PRIORITY_BELOW_NORMAL; // -1
  698. case Thread::LowestPriority: return THREAD_PRIORITY_LOWEST; // -2
  699. case Thread::IdlePriority: return THREAD_PRIORITY_IDLE; // -15
  700. }
  701. return THREAD_PRIORITY_NORMAL;
  702. }
  703. /* static */
  704. Thread::ThreadPriority Thread::GetOVRPriority(int osPriority)
  705. {
  706. // If the process is REALTIME_PRIORITY_CLASS then it could have priority values 3 through14 and -3 through -14.
  707. // As a result, it's possible for those cases that an unknown/invalid ThreadPriority enum be returned. However,
  708. // in practice we don't expect to be using such processes.
  709. // The ThreadPriority types aren't linearly distributed, so we need to check for some values explicitly.
  710. if(osPriority == THREAD_PRIORITY_TIME_CRITICAL)
  711. return Thread::CriticalPriority;
  712. if(osPriority == THREAD_PRIORITY_IDLE)
  713. return Thread::IdlePriority;
  714. return (ThreadPriority)(Thread::NormalPriority - osPriority);
  715. }
  716. Thread::ThreadPriority Thread::GetPriority()
  717. {
  718. int osPriority = ::GetThreadPriority(ThreadHandle);
  719. if(osPriority != THREAD_PRIORITY_ERROR_RETURN)
  720. {
  721. return GetOVRPriority(osPriority);
  722. }
  723. return NormalPriority;
  724. }
  725. /* static */
  726. Thread::ThreadPriority Thread::GetCurrentPriority()
  727. {
  728. int osPriority = ::GetThreadPriority(::GetCurrentThread());
  729. if(osPriority != THREAD_PRIORITY_ERROR_RETURN)
  730. {
  731. return GetOVRPriority(osPriority);
  732. }
  733. return NormalPriority;
  734. }
  735. bool Thread::SetPriority(ThreadPriority p)
  736. {
  737. BOOL ret = ::SetThreadPriority(ThreadHandle, Thread::GetOSPriority(p));
  738. return (ret != FALSE);
  739. }
  740. /* static */
  741. bool Thread::SetCurrentPriority(ThreadPriority p)
  742. {
  743. BOOL ret = ::SetThreadPriority(::GetCurrentThread(), Thread::GetOSPriority(p));
  744. return (ret != FALSE);
  745. }
  746. // The actual first function called on thread start
  747. #if defined(OVR_OS_WIN32)
  748. unsigned WINAPI Thread_Win32StartFn(void * phandle)
  749. #else // Other Micorosft OSs...
  750. DWORD WINAPI Thread_Win32StartFn(void *phandle)
  751. #endif
  752. {
  753. Thread * pthread = (Thread*)phandle;
  754. if (pthread->Processor != -1)
  755. {
  756. DWORD_PTR ret = SetThreadAffinityMask(GetCurrentThread(), (DWORD)pthread->Processor);
  757. if (ret == 0)
  758. OVR_DEBUG_LOG(("Could not set hardware processor for the thread"));
  759. }
  760. BOOL ret = ::SetThreadPriority(GetCurrentThread(), Thread::GetOSPriority(pthread->Priority));
  761. if (ret == 0)
  762. OVR_DEBUG_LOG(("Could not set thread priority"));
  763. OVR_UNUSED(ret);
  764. // Ensure that ThreadId is assigned once thread is running, in case
  765. // beginthread hasn't filled it in yet.
  766. pthread->IdValue = (ThreadId)::GetCurrentThreadId();
  767. DWORD result = pthread->PRun();
  768. // Signal the thread as done and release it atomically.
  769. pthread->FinishAndRelease();
  770. // At this point Thread object might be dead; however we can still pass
  771. // it to RemoveRunningThread since it is only used as a key there.
  772. ThreadList::RemoveRunningThread(pthread);
  773. return (unsigned) result;
  774. }
  775. bool Thread::Start(ThreadState initialState)
  776. {
  777. if (initialState == NotRunning)
  778. return 0;
  779. if (GetThreadState() != NotRunning)
  780. {
  781. OVR_DEBUG_LOG(("Thread::Start failed - thread %p already running", this));
  782. return 0;
  783. }
  784. // Free old thread handle before creating the new one
  785. CleanupSystemThread();
  786. // AddRef to us until the thread is finished.
  787. AddRef();
  788. ThreadList::AddRunningThread(this);
  789. ExitCode = 0;
  790. SuspendCount = 0;
  791. ThreadFlags = (initialState == Running) ? 0 : OVR_THREAD_START_SUSPENDED;
  792. #if defined(OVR_OS_WIN32)
  793. ThreadHandle = (HANDLE) _beginthreadex(0, (unsigned)StackSize,
  794. Thread_Win32StartFn, this, 0, (unsigned*)&IdValue);
  795. #else // Other Micorosft OSs...
  796. DWORD TheThreadId;
  797. ThreadHandle = CreateThread(0, (unsigned)StackSize,
  798. Thread_Win32StartFn, this, 0, &TheThreadId);
  799. IdValue = (ThreadId)TheThreadId;
  800. #endif
  801. // Failed? Fail the function
  802. if (ThreadHandle == 0)
  803. {
  804. ThreadFlags = 0;
  805. Release();
  806. ThreadList::RemoveRunningThread(this);
  807. return 0;
  808. }
  809. return 1;
  810. }
  811. // Suspend the thread until resumed
  812. bool Thread::Suspend()
  813. {
  814. // Can't suspend a thread that wasn't started
  815. if (!(ThreadFlags & OVR_THREAD_STARTED))
  816. return 0;
  817. if (::SuspendThread(ThreadHandle) != 0xFFFFFFFF)
  818. {
  819. SuspendCount++;
  820. return 1;
  821. }
  822. return 0;
  823. }
  824. // Resumes currently suspended thread
  825. bool Thread::Resume()
  826. {
  827. // Can't suspend a thread that wasn't started
  828. if (!(ThreadFlags & OVR_THREAD_STARTED))
  829. return 0;
  830. // Decrement count, and resume thread if it is 0
  831. int32_t oldCount = SuspendCount.ExchangeAdd_Acquire(-1);
  832. if (oldCount >= 1)
  833. {
  834. if (oldCount == 1)
  835. {
  836. if (::ResumeThread(ThreadHandle) != 0xFFFFFFFF)
  837. {
  838. return 1;
  839. }
  840. }
  841. else
  842. {
  843. return 1;
  844. }
  845. }
  846. return 0;
  847. }
  848. // Quits with an exit code
  849. void Thread::Exit(int exitCode)
  850. {
  851. // Can only exist the current thread.
  852. // MA: Don't use TLS for now.
  853. //if (GetThread() != this)
  854. // return;
  855. // Call the virtual OnExit function.
  856. OnExit();
  857. // Signal this thread object as done and release it's references.
  858. FinishAndRelease();
  859. ThreadList::RemoveRunningThread(this);
  860. // Call the exit function.
  861. #if defined(OVR_OS_WIN32) // _endthreadex doesn't exist on other Microsoft OSs and instead we need to call ExitThread directly.
  862. _endthreadex((unsigned)exitCode);
  863. #else
  864. ExitThread((unsigned)exitCode);
  865. #endif
  866. }
  867. void Thread::CleanupSystemThread()
  868. {
  869. if (ThreadHandle != 0)
  870. {
  871. ::CloseHandle(ThreadHandle);
  872. ThreadHandle = 0;
  873. }
  874. }
  875. // *** Sleep functions
  876. // static
  877. bool Thread::Sleep(unsigned secs)
  878. {
  879. ::Sleep(secs*1000);
  880. return 1;
  881. }
  882. // static
  883. bool Thread::MSleep(unsigned msecs)
  884. {
  885. ::Sleep(msecs);
  886. return 1;
  887. }
  888. // static
  889. void Thread::YieldCurrentThread()
  890. {
  891. YieldProcessor();
  892. }
  893. void Thread::SetThreadName( const char* name )
  894. {
  895. if(IdValue)
  896. SetThreadName(name, IdValue);
  897. // Else we don't know what thread to name. We can save the name and wait until the thread is created.
  898. }
  899. void Thread::SetThreadName(const char* name, ThreadId threadId)
  900. {
  901. #if !defined(OVR_BUILD_SHIPPING) || defined(OVR_BUILD_PROFILING)
  902. // http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  903. #pragma pack(push,8)
  904. struct THREADNAME_INFO {
  905. DWORD dwType; // Must be 0x1000
  906. LPCSTR szName; // Pointer to name (in user address space)
  907. DWORD dwThreadID; // Thread ID (-1 for caller thread)
  908. DWORD dwFlags; // Reserved for future use; must be zero
  909. };
  910. union TNIUnion
  911. {
  912. THREADNAME_INFO tni;
  913. ULONG_PTR upArray[4];
  914. };
  915. #pragma pack(pop)
  916. TNIUnion tniUnion = { 0x1000, name, (DWORD)threadId, 0 };
  917. __try
  918. {
  919. RaiseException( 0x406D1388, 0, OVR_ARRAY_COUNT(tniUnion.upArray), tniUnion.upArray);
  920. }
  921. __except( GetExceptionCode()==0x406D1388 ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER )
  922. {
  923. return;
  924. }
  925. #endif // OVR_BUILD_SHIPPING
  926. }
  927. void Thread::SetCurrentThreadName( const char* name )
  928. {
  929. SetThreadName(name, (ThreadId)::GetCurrentThreadId());
  930. }
  931. void Thread::GetThreadName(char* name, size_t /*nameCapacity*/, ThreadId /*threadId*/)
  932. {
  933. // Not possible on Windows.
  934. name[0] = 0;
  935. }
  936. void Thread::GetCurrentThreadName(char* name, size_t /*nameCapacity*/)
  937. {
  938. // Not possible on Windows.
  939. name[0] = 0;
  940. }
  941. // static
  942. int Thread::GetCPUCount()
  943. {
  944. SYSTEM_INFO sysInfo;
  945. #if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0501) // GetNativeSystemInfo requires WinXP+ and a corresponding SDK (0x0501) or later.
  946. GetNativeSystemInfo(&sysInfo);
  947. #else
  948. GetSystemInfo(&sysInfo);
  949. #endif
  950. return (int) sysInfo.dwNumberOfProcessors;
  951. }
  952. // Returns the unique Id of a thread it is called on, intended for
  953. // comparison purposes.
  954. ThreadId GetCurrentThreadId()
  955. {
  956. return (ThreadId)::GetCurrentThreadId();
  957. }
  958. } // OVR
  959. #endif