NvThreadConfig.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. /*
  2. NvThreadConfig.cpp : A simple wrapper class to define threading and mutex locks.
  3. */
  4. /*!
  5. **
  6. ** Copyright (c) 2009 by John W. Ratcliff mailto:[email protected]
  7. **
  8. ** Portions of this source has been released with the PhysXViewer application, as well as
  9. ** Rocket, CreateDynamics, ODF, and as a number of sample code snippets.
  10. **
  11. ** If you find this code useful or you are feeling particularily generous I would
  12. ** ask that you please go to http://www.amillionpixels.us and make a donation
  13. ** to Troy DeMolay.
  14. **
  15. ** DeMolay is a youth group for young men between the ages of 12 and 21.
  16. ** It teaches strong moral principles, as well as leadership skills and
  17. ** public speaking. The donations page uses the 'pay for pixels' paradigm
  18. ** where, in this case, a pixel is only a single penny. Donations can be
  19. ** made for as small as $4 or as high as a $100 block. Each person who donates
  20. ** will get a link to their own site as well as acknowledgement on the
  21. ** donations blog located here http://www.amillionpixels.blogspot.com/
  22. **
  23. ** If you wish to contact me you can use the following methods:
  24. **
  25. ** Skype ID: jratcliff63367
  26. ** Yahoo: jratcliff63367
  27. ** AOL: jratcliff1961
  28. ** email: [email protected]
  29. **
  30. **
  31. ** The MIT license:
  32. **
  33. ** Permission is hereby granted, free of charge, to any person obtaining a copy
  34. ** of this software and associated documentation files (the "Software"), to deal
  35. ** in the Software without restriction, including without limitation the rights
  36. ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37. ** copies of the Software, and to permit persons to whom the Software is furnished
  38. ** to do so, subject to the following conditions:
  39. **
  40. ** The above copyright notice and this permission notice shall be included in all
  41. ** copies or substantial portions of the Software.
  42. ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  43. ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  44. ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  45. ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  46. ** WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  47. ** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  48. */
  49. #include <cassert>
  50. #include "NvThreadConfig.h"
  51. #if defined(WIN32)
  52. #define _WIN32_WINNT 0x400
  53. #include <windows.h>
  54. #pragma comment(lib,"winmm.lib")
  55. // #ifndef _WIN32_WINNT
  56. // #endif
  57. // #include <windows.h>
  58. //#include <winbase.h>
  59. #endif
  60. #if defined(_XBOX)
  61. #include <xtl.h>
  62. #endif
  63. #if defined(__linux__) || defined( __APPLE__ )
  64. //#include <sys/time.h>
  65. #include <time.h>
  66. #include <unistd.h>
  67. #include <errno.h>
  68. #define __stdcall
  69. #endif
  70. #if defined( __APPLE__ )
  71. #include <sys/time.h>
  72. #endif
  73. #if defined(__APPLE__) || defined(__linux__)
  74. #include <pthread.h>
  75. #endif
  76. #if defined( __APPLE__ )
  77. #define PTHREAD_MUTEX_RECURSIVE_NP PTHREAD_MUTEX_RECURSIVE
  78. #endif
  79. #ifdef NDEBUG
  80. #define VERIFY( x ) (x)
  81. #else
  82. #define VERIFY( x ) assert((x))
  83. #endif
  84. namespace CONVEX_DECOMPOSITION
  85. {
  86. NxU32 tc_timeGetTime(void)
  87. {
  88. #if defined(__linux__)
  89. struct timespec ts;
  90. clock_gettime(CLOCK_REALTIME, &ts);
  91. return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
  92. #elif defined( __APPLE__ )
  93. struct timeval tp;
  94. gettimeofday(&tp, (struct timezone *)0);
  95. return tp.tv_sec * 1000 + tp.tv_usec / 1000;
  96. #elif defined( _XBOX )
  97. return GetTickCount();
  98. #else
  99. return timeGetTime();
  100. #endif
  101. }
  102. void tc_sleep(NxU32 ms)
  103. {
  104. #if defined(__linux__) || defined( __APPLE__ )
  105. usleep(ms * 1000);
  106. #else
  107. Sleep(ms);
  108. #endif
  109. }
  110. void tc_spinloop()
  111. {
  112. #if defined( _XBOX )
  113. // Pause would do nothing on the Xbox. Threads are not scheduled.
  114. #elif defined( _WIN64 )
  115. YieldProcessor( );
  116. #elif defined( __APPLE__ )
  117. pthread_yield_np();
  118. #elif defined(__linux__)
  119. #if defined(_POSIX_PRIORITY_SCHEDULING)
  120. sched_yield();
  121. #else
  122. asm("pause");
  123. #endif
  124. #elif
  125. __asm { pause };
  126. #endif
  127. }
  128. void tc_interlockedExchange(void *dest, const int64_t exchange)
  129. {
  130. #if defined( __linux__ ) || defined( __APPLE__ )
  131. // not working
  132. assert(false);
  133. //__sync_lock_test_and_set((int64_t*)dest, exchange);
  134. #elif defined( _XBOX ) || defined( _WIN64 )
  135. InterlockedExchange((volatile LONG *)dest, exchange);
  136. #else
  137. __asm
  138. {
  139. mov ebx, dword ptr [exchange]
  140. mov ecx, dword ptr [exchange + 4]
  141. mov edi, dest
  142. mov eax, dword ptr [edi]
  143. mov edx, dword ptr [edi + 4]
  144. jmp start
  145. retry:
  146. pause
  147. start:
  148. lock cmpxchg8b [edi]
  149. jnz retry
  150. };
  151. #endif
  152. }
  153. NxI32 tc_interlockedCompareExchange(void *dest, NxI32 exchange, NxI32 compare)
  154. {
  155. #if defined( __linux__ ) || defined( __APPLE__ )
  156. // not working
  157. assert(false);
  158. return 0;
  159. //return __sync_val_compare_and_swap((uintptr_t*)dest, exchange, compare);
  160. //return __sync_bool_compare_and_swap((uintptr_t*)dest, exchange, compare);
  161. #elif defined( _XBOX ) || defined( _WIN64 )
  162. return InterlockedCompareExchange((volatile LONG *)dest, exchange, compare);
  163. #else
  164. char _ret;
  165. //
  166. __asm
  167. {
  168. mov edx, [dest]
  169. mov eax, [compare]
  170. mov ecx, [exchange]
  171. lock cmpxchg [edx], ecx
  172. setz al
  173. mov byte ptr [_ret], al
  174. }
  175. //
  176. return _ret;
  177. #endif
  178. }
  179. NxI32 tc_interlockedCompareExchange(void *dest, const NxI32 exchange1, const NxI32 exchange2, const NxI32 compare1, const NxI32 compare2)
  180. {
  181. #if defined( __linux__ ) || defined( __APPLE__ )
  182. // not working
  183. assert(false);
  184. return 0;
  185. //uint64_t exchange = ((uint64_t)exchange1 << 32) | (uint64_t)exchange2;
  186. //uint64_t compare = ((uint64_t)compare1 << 32) | (uint64_t)compare2;
  187. //return __sync_bool_compare_and_swap((int64_t*)dest, exchange, compare);
  188. #elif defined( _XBOX ) || defined( _WIN64 )
  189. assert(false);
  190. return 0;
  191. #else
  192. char _ret;
  193. //
  194. __asm
  195. {
  196. mov ebx, [exchange1]
  197. mov ecx, [exchange2]
  198. mov edi, [dest]
  199. mov eax, [compare1]
  200. mov edx, [compare2]
  201. lock cmpxchg8b [edi]
  202. setz al
  203. mov byte ptr [_ret], al
  204. }
  205. //
  206. return _ret;
  207. #endif
  208. }
  209. class MyThreadMutex : public ThreadMutex
  210. {
  211. public:
  212. MyThreadMutex(void)
  213. {
  214. #if defined(WIN32) || defined(_XBOX)
  215. InitializeCriticalSection(&m_Mutex);
  216. #elif defined(__APPLE__) || defined(__linux__)
  217. pthread_mutexattr_t mutexAttr; // Mutex Attribute
  218. VERIFY( pthread_mutexattr_init(&mutexAttr) == 0 );
  219. VERIFY( pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE_NP) == 0 );
  220. VERIFY( pthread_mutex_init(&m_Mutex, &mutexAttr) == 0 );
  221. VERIFY( pthread_mutexattr_destroy(&mutexAttr) == 0 );
  222. #endif
  223. }
  224. ~MyThreadMutex(void)
  225. {
  226. #if defined(WIN32) || defined(_XBOX)
  227. DeleteCriticalSection(&m_Mutex);
  228. #elif defined(__APPLE__) || defined(__linux__)
  229. VERIFY( pthread_mutex_destroy(&m_Mutex) == 0 );
  230. #endif
  231. }
  232. void lock(void)
  233. {
  234. #if defined(WIN32) || defined(_XBOX)
  235. EnterCriticalSection(&m_Mutex);
  236. #elif defined(__APPLE__) || defined(__linux__)
  237. VERIFY( pthread_mutex_lock(&m_Mutex) == 0 );
  238. #endif
  239. }
  240. bool tryLock(void)
  241. {
  242. #if defined(WIN32) || defined(_XBOX)
  243. bool bRet = false;
  244. //assert(("TryEnterCriticalSection seems to not work on XP???", 0));
  245. bRet = TryEnterCriticalSection(&m_Mutex) ? true : false;
  246. return bRet;
  247. #elif defined(__APPLE__) || defined(__linux__)
  248. NxI32 result = pthread_mutex_trylock(&m_Mutex);
  249. return (result == 0);
  250. #endif
  251. }
  252. void unlock(void)
  253. {
  254. #if defined(WIN32) || defined(_XBOX)
  255. LeaveCriticalSection(&m_Mutex);
  256. #elif defined(__APPLE__) || defined(__linux__)
  257. VERIFY( pthread_mutex_unlock(&m_Mutex) == 0 );
  258. #endif
  259. }
  260. private:
  261. #if defined(WIN32) || defined(_XBOX)
  262. CRITICAL_SECTION m_Mutex;
  263. #elif defined(__APPLE__) || defined(__linux__)
  264. pthread_mutex_t m_Mutex;
  265. #endif
  266. };
  267. ThreadMutex * tc_createThreadMutex(void)
  268. {
  269. MyThreadMutex *m = new MyThreadMutex;
  270. return static_cast< ThreadMutex *>(m);
  271. }
  272. void tc_releaseThreadMutex(ThreadMutex *tm)
  273. {
  274. MyThreadMutex *m = static_cast< MyThreadMutex *>(tm);
  275. delete m;
  276. }
  277. #if defined(WIN32) || defined(_XBOX)
  278. static unsigned long __stdcall _ThreadWorkerFunc(LPVOID arg);
  279. #elif defined(__APPLE__) || defined(__linux__)
  280. static void* _ThreadWorkerFunc(void* arg);
  281. #endif
  282. class MyThread : public Thread
  283. {
  284. public:
  285. MyThread(ThreadInterface *iface)
  286. {
  287. mInterface = iface;
  288. #if defined(WIN32) || defined(_XBOX)
  289. mThread = CreateThread(0, 0, _ThreadWorkerFunc, this, 0, 0);
  290. #elif defined(__APPLE__) || defined(__linux__)
  291. VERIFY( pthread_create(&mThread, NULL, _ThreadWorkerFunc, this) == 0 );
  292. #endif
  293. }
  294. ~MyThread(void)
  295. {
  296. #if defined(WIN32) || defined(_XBOX)
  297. if ( mThread )
  298. {
  299. CloseHandle(mThread);
  300. mThread = 0;
  301. }
  302. #endif
  303. }
  304. void onJobExecute(void)
  305. {
  306. mInterface->threadMain();
  307. }
  308. private:
  309. ThreadInterface *mInterface;
  310. #if defined(WIN32) || defined(_XBOX)
  311. HANDLE mThread;
  312. #elif defined(__APPLE__) || defined(__linux__)
  313. pthread_t mThread;
  314. #endif
  315. };
  316. Thread * tc_createThread(ThreadInterface *tinterface)
  317. {
  318. MyThread *m = new MyThread(tinterface);
  319. return static_cast< Thread *>(m);
  320. }
  321. void tc_releaseThread(Thread *t)
  322. {
  323. MyThread *m = static_cast<MyThread *>(t);
  324. delete m;
  325. }
  326. #if defined(WIN32) || defined(_XBOX)
  327. static unsigned long __stdcall _ThreadWorkerFunc(LPVOID arg)
  328. #elif defined(__APPLE__) || defined(__linux__)
  329. static void* _ThreadWorkerFunc(void* arg)
  330. #endif
  331. {
  332. MyThread *worker = (MyThread *) arg;
  333. worker->onJobExecute();
  334. return 0;
  335. }
  336. class MyThreadEvent : public ThreadEvent
  337. {
  338. public:
  339. MyThreadEvent(void)
  340. {
  341. #if defined(WIN32) || defined(_XBOX)
  342. mEvent = ::CreateEventA(NULL,TRUE,TRUE,"ThreadEvent");
  343. #elif defined(__APPLE__) || defined(__linux__)
  344. pthread_mutexattr_t mutexAttr; // Mutex Attribute
  345. VERIFY( pthread_mutexattr_init(&mutexAttr) == 0 );
  346. VERIFY( pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE_NP) == 0 );
  347. VERIFY( pthread_mutex_init(&mEventMutex, &mutexAttr) == 0 );
  348. VERIFY( pthread_mutexattr_destroy(&mutexAttr) == 0 );
  349. VERIFY( pthread_cond_init(&mEvent, NULL) == 0 );
  350. #endif
  351. }
  352. ~MyThreadEvent(void)
  353. {
  354. #if defined(WIN32) || defined(_XBOX)
  355. if ( mEvent )
  356. {
  357. ::CloseHandle(mEvent);
  358. }
  359. #elif defined(__APPLE__) || defined(__linux__)
  360. VERIFY( pthread_cond_destroy(&mEvent) == 0 );
  361. VERIFY( pthread_mutex_destroy(&mEventMutex) == 0 );
  362. #endif
  363. }
  364. virtual void setEvent(void) // signal the event
  365. {
  366. #if defined(WIN32) || defined(_XBOX)
  367. if ( mEvent )
  368. {
  369. ::SetEvent(mEvent);
  370. }
  371. #elif defined(__APPLE__) || defined(__linux__)
  372. VERIFY( pthread_mutex_lock(&mEventMutex) == 0 );
  373. VERIFY( pthread_cond_signal(&mEvent) == 0 );
  374. VERIFY( pthread_mutex_unlock(&mEventMutex) == 0 );
  375. #endif
  376. }
  377. void resetEvent(void)
  378. {
  379. #if defined(WIN32) || defined(_XBOX)
  380. if ( mEvent )
  381. {
  382. ::ResetEvent(mEvent);
  383. }
  384. #endif
  385. }
  386. virtual void waitForSingleObject(NxU32 ms)
  387. {
  388. #if defined(WIN32) || defined(_XBOX)
  389. if ( mEvent )
  390. {
  391. ::WaitForSingleObject(mEvent,ms);
  392. }
  393. #elif defined(__APPLE__) || defined(__linux__)
  394. VERIFY( pthread_mutex_lock(&mEventMutex) == 0 );
  395. if (ms == 0xffffffff)
  396. {
  397. VERIFY( pthread_cond_wait(&mEvent, &mEventMutex) == 0 );
  398. }
  399. else
  400. {
  401. struct timespec ts;
  402. #ifdef __APPLE__
  403. struct timeval tp;
  404. gettimeofday(&tp, (struct timezone *)0);
  405. ts.tv_nsec = tp.tv_usec * 1000;
  406. ts.tv_sec = tp.tv_sec;
  407. #else
  408. clock_gettime(CLOCK_REALTIME, &ts);
  409. #endif
  410. ts.tv_nsec += ms * 1000000;
  411. ts.tv_sec += ts.tv_nsec / 1000000000;
  412. ts.tv_nsec %= 1000000000;
  413. NxI32 result = pthread_cond_timedwait(&mEvent, &mEventMutex, &ts);
  414. assert(result == 0 || result == ETIMEDOUT);
  415. }
  416. VERIFY( pthread_mutex_unlock(&mEventMutex) == 0 );
  417. #endif
  418. }
  419. private:
  420. #if defined(WIN32) || defined(_XBOX)
  421. HANDLE mEvent;
  422. #elif defined(__APPLE__) || defined(__linux__)
  423. pthread_mutex_t mEventMutex;
  424. pthread_cond_t mEvent;
  425. #endif
  426. };
  427. ThreadEvent * tc_createThreadEvent(void)
  428. {
  429. MyThreadEvent *m = new MyThreadEvent;
  430. return static_cast<ThreadEvent *>(m);
  431. }
  432. void tc_releaseThreadEvent(ThreadEvent *t)
  433. {
  434. MyThreadEvent *m = static_cast< MyThreadEvent *>(t);
  435. delete m;
  436. }
  437. }; // end of namespace