2
0

btThreadSupportPosix.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2018 Erwin Coumans http://bulletphysics.com
  4. This software is provided 'as-is', without any express or implied warranty.
  5. In no event will the authors be held liable for any damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it freely,
  8. subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  10. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  11. 3. This notice may not be removed or altered from any source distribution.
  12. */
  13. #if BT_THREADSAFE && !defined( _WIN32 )
  14. #include "LinearMath/btScalar.h"
  15. #include "LinearMath/btAlignedObjectArray.h"
  16. #include "LinearMath/btThreads.h"
  17. #include "LinearMath/btMinMax.h"
  18. #include "btThreadSupportInterface.h"
  19. #include <stdio.h>
  20. #include <errno.h>
  21. #include <unistd.h>
  22. #ifndef _XOPEN_SOURCE
  23. #define _XOPEN_SOURCE 600 //for definition of pthread_barrier_t, see http://pages.cs.wisc.edu/~travitch/pthreads_primer.html
  24. #endif //_XOPEN_SOURCE
  25. #include <pthread.h>
  26. #include <semaphore.h>
  27. #include <unistd.h> //for sysconf
  28. ///
  29. /// getNumHardwareThreads()
  30. ///
  31. ///
  32. /// https://stackoverflow.com/questions/150355/programmatically-find-the-number-of-cores-on-a-machine
  33. ///
  34. #if __cplusplus >= 201103L
  35. #include <thread>
  36. int btGetNumHardwareThreads()
  37. {
  38. return btMin<int>(BT_MAX_THREAD_COUNT, std::thread::hardware_concurrency());
  39. }
  40. #else
  41. int btGetNumHardwareThreads()
  42. {
  43. return btMin<int>(BT_MAX_THREAD_COUNT, sysconf( _SC_NPROCESSORS_ONLN ));
  44. }
  45. #endif
  46. // btThreadSupportPosix helps to initialize/shutdown libspe2, start/stop SPU tasks and communication
  47. class btThreadSupportPosix : public btThreadSupportInterface
  48. {
  49. public:
  50. struct btThreadStatus
  51. {
  52. int m_taskId;
  53. int m_commandId;
  54. int m_status;
  55. ThreadFunc m_userThreadFunc;
  56. void* m_userPtr; //for taskDesc etc
  57. pthread_t thread;
  58. //each tread will wait until this signal to start its work
  59. sem_t* startSemaphore;
  60. // this is a copy of m_mainSemaphore,
  61. //each tread will signal once it is finished with its work
  62. sem_t* m_mainSemaphore;
  63. unsigned long threadUsed;
  64. };
  65. private:
  66. typedef unsigned long long UINT64;
  67. btAlignedObjectArray<btThreadStatus> m_activeThreadStatus;
  68. // m_mainSemaphoresemaphore will signal, if and how many threads are finished with their work
  69. sem_t* m_mainSemaphore;
  70. int m_numThreads;
  71. UINT64 m_startedThreadsMask;
  72. void startThreads( const ConstructionInfo& threadInfo );
  73. void stopThreads();
  74. int waitForResponse();
  75. public:
  76. btThreadSupportPosix( const ConstructionInfo& threadConstructionInfo );
  77. virtual ~btThreadSupportPosix();
  78. virtual int getNumWorkerThreads() const BT_OVERRIDE { return m_numThreads; }
  79. // TODO: return the number of logical processors sharing the first L3 cache
  80. virtual int getCacheFriendlyNumThreads() const BT_OVERRIDE { return m_numThreads + 1; }
  81. // TODO: detect if CPU has hyperthreading enabled
  82. virtual int getLogicalToPhysicalCoreRatio() const BT_OVERRIDE { return 1; }
  83. virtual void runTask( int threadIndex, void* userData ) BT_OVERRIDE;
  84. virtual void waitForAllTasks() BT_OVERRIDE;
  85. virtual btCriticalSection* createCriticalSection() BT_OVERRIDE;
  86. virtual void deleteCriticalSection( btCriticalSection* criticalSection ) BT_OVERRIDE;
  87. };
  88. #define checkPThreadFunction(returnValue) \
  89. if(0 != returnValue) { \
  90. printf("PThread problem at line %i in file %s: %i %d\n", __LINE__, __FILE__, returnValue, errno); \
  91. }
  92. // The number of threads should be equal to the number of available cores
  93. // Todo: each worker should be linked to a single core, using SetThreadIdealProcessor.
  94. btThreadSupportPosix::btThreadSupportPosix( const ConstructionInfo& threadConstructionInfo )
  95. {
  96. startThreads( threadConstructionInfo );
  97. }
  98. // cleanup/shutdown Libspe2
  99. btThreadSupportPosix::~btThreadSupportPosix()
  100. {
  101. stopThreads();
  102. }
  103. #if (defined (__APPLE__))
  104. #define NAMED_SEMAPHORES
  105. #endif
  106. static sem_t* createSem( const char* baseName )
  107. {
  108. static int semCount = 0;
  109. #ifdef NAMED_SEMAPHORES
  110. /// Named semaphore begin
  111. char name[ 32 ];
  112. snprintf( name, 32, "/%8.s-%4.d-%4.4d", baseName, getpid(), semCount++ );
  113. sem_t* tempSem = sem_open( name, O_CREAT, 0600, 0 );
  114. if ( tempSem != reinterpret_cast<sem_t *>( SEM_FAILED ) )
  115. {
  116. // printf("Created \"%s\" Semaphore %p\n", name, tempSem);
  117. }
  118. else
  119. {
  120. //printf("Error creating Semaphore %d\n", errno);
  121. exit( -1 );
  122. }
  123. /// Named semaphore end
  124. #else
  125. sem_t* tempSem = new sem_t;
  126. checkPThreadFunction( sem_init( tempSem, 0, 0 ) );
  127. #endif
  128. return tempSem;
  129. }
  130. static void destroySem( sem_t* semaphore )
  131. {
  132. #ifdef NAMED_SEMAPHORES
  133. checkPThreadFunction( sem_close( semaphore ) );
  134. #else
  135. checkPThreadFunction( sem_destroy( semaphore ) );
  136. delete semaphore;
  137. #endif
  138. }
  139. static void *threadFunction( void *argument )
  140. {
  141. btThreadSupportPosix::btThreadStatus* status = ( btThreadSupportPosix::btThreadStatus* )argument;
  142. while ( 1 )
  143. {
  144. checkPThreadFunction( sem_wait( status->startSemaphore ) );
  145. void* userPtr = status->m_userPtr;
  146. if ( userPtr )
  147. {
  148. btAssert( status->m_status );
  149. status->m_userThreadFunc( userPtr );
  150. status->m_status = 2;
  151. checkPThreadFunction( sem_post( status->m_mainSemaphore ) );
  152. status->threadUsed++;
  153. }
  154. else
  155. {
  156. //exit Thread
  157. status->m_status = 3;
  158. checkPThreadFunction( sem_post( status->m_mainSemaphore ) );
  159. printf( "Thread with taskId %i exiting\n", status->m_taskId );
  160. break;
  161. }
  162. }
  163. printf( "Thread TERMINATED\n" );
  164. return 0;
  165. }
  166. ///send messages to SPUs
  167. void btThreadSupportPosix::runTask( int threadIndex, void* userData )
  168. {
  169. ///we should spawn an SPU task here, and in 'waitForResponse' it should wait for response of the (one of) the first tasks that finished
  170. btThreadStatus& threadStatus = m_activeThreadStatus[ threadIndex ];
  171. btAssert( threadIndex >= 0 );
  172. btAssert( threadIndex < m_activeThreadStatus.size() );
  173. threadStatus.m_commandId = 1;
  174. threadStatus.m_status = 1;
  175. threadStatus.m_userPtr = userData;
  176. m_startedThreadsMask |= UINT64( 1 ) << threadIndex;
  177. // fire event to start new task
  178. checkPThreadFunction( sem_post( threadStatus.startSemaphore ) );
  179. }
  180. ///check for messages from SPUs
  181. int btThreadSupportPosix::waitForResponse()
  182. {
  183. ///We should wait for (one of) the first tasks to finish (or other SPU messages), and report its response
  184. ///A possible response can be 'yes, SPU handled it', or 'no, please do a PPU fallback'
  185. btAssert( m_activeThreadStatus.size() );
  186. // wait for any of the threads to finish
  187. checkPThreadFunction( sem_wait( m_mainSemaphore ) );
  188. // get at least one thread which has finished
  189. size_t last = -1;
  190. for ( size_t t = 0; t < size_t( m_activeThreadStatus.size() ); ++t )
  191. {
  192. if ( 2 == m_activeThreadStatus[ t ].m_status )
  193. {
  194. last = t;
  195. break;
  196. }
  197. }
  198. btThreadStatus& threadStatus = m_activeThreadStatus[ last ];
  199. btAssert( threadStatus.m_status > 1 );
  200. threadStatus.m_status = 0;
  201. // need to find an active spu
  202. btAssert( last >= 0 );
  203. m_startedThreadsMask &= ~( UINT64( 1 ) << last );
  204. return last;
  205. }
  206. void btThreadSupportPosix::waitForAllTasks()
  207. {
  208. while ( m_startedThreadsMask )
  209. {
  210. waitForResponse();
  211. }
  212. }
  213. void btThreadSupportPosix::startThreads( const ConstructionInfo& threadConstructionInfo )
  214. {
  215. m_numThreads = btGetNumHardwareThreads() - 1; // main thread exists already
  216. printf( "%s creating %i threads.\n", __FUNCTION__, m_numThreads );
  217. m_activeThreadStatus.resize( m_numThreads );
  218. m_startedThreadsMask = 0;
  219. m_mainSemaphore = createSem( "main" );
  220. //checkPThreadFunction(sem_wait(mainSemaphore));
  221. for ( int i = 0; i < m_numThreads; i++ )
  222. {
  223. printf( "starting thread %d\n", i );
  224. btThreadStatus& threadStatus = m_activeThreadStatus[ i ];
  225. threadStatus.startSemaphore = createSem( "threadLocal" );
  226. checkPThreadFunction( pthread_create( &threadStatus.thread, NULL, &threadFunction, (void*) &threadStatus ) );
  227. threadStatus.m_userPtr = 0;
  228. threadStatus.m_taskId = i;
  229. threadStatus.m_commandId = 0;
  230. threadStatus.m_status = 0;
  231. threadStatus.m_mainSemaphore = m_mainSemaphore;
  232. threadStatus.m_userThreadFunc = threadConstructionInfo.m_userThreadFunc;
  233. threadStatus.threadUsed = 0;
  234. printf( "started thread %d \n", i );
  235. }
  236. }
  237. ///tell the task scheduler we are done with the SPU tasks
  238. void btThreadSupportPosix::stopThreads()
  239. {
  240. for ( size_t t = 0; t < size_t( m_activeThreadStatus.size() ); ++t )
  241. {
  242. btThreadStatus& threadStatus = m_activeThreadStatus[ t ];
  243. printf( "%s: Thread %i used: %ld\n", __FUNCTION__, int( t ), threadStatus.threadUsed );
  244. threadStatus.m_userPtr = 0;
  245. checkPThreadFunction( sem_post( threadStatus.startSemaphore ) );
  246. checkPThreadFunction( sem_wait( m_mainSemaphore ) );
  247. printf( "destroy semaphore\n" );
  248. destroySem( threadStatus.startSemaphore );
  249. printf( "semaphore destroyed\n" );
  250. checkPThreadFunction( pthread_join( threadStatus.thread, 0 ) );
  251. }
  252. printf( "destroy main semaphore\n" );
  253. destroySem( m_mainSemaphore );
  254. printf( "main semaphore destroyed\n" );
  255. m_activeThreadStatus.clear();
  256. }
  257. class btCriticalSectionPosix : public btCriticalSection
  258. {
  259. pthread_mutex_t m_mutex;
  260. public:
  261. btCriticalSectionPosix()
  262. {
  263. pthread_mutex_init( &m_mutex, NULL );
  264. }
  265. virtual ~btCriticalSectionPosix()
  266. {
  267. pthread_mutex_destroy( &m_mutex );
  268. }
  269. virtual void lock()
  270. {
  271. pthread_mutex_lock( &m_mutex );
  272. }
  273. virtual void unlock()
  274. {
  275. pthread_mutex_unlock( &m_mutex );
  276. }
  277. };
  278. btCriticalSection* btThreadSupportPosix::createCriticalSection()
  279. {
  280. return new btCriticalSectionPosix();
  281. }
  282. void btThreadSupportPosix::deleteCriticalSection( btCriticalSection* cs )
  283. {
  284. delete cs;
  285. }
  286. btThreadSupportInterface* btThreadSupportInterface::create( const ConstructionInfo& info )
  287. {
  288. return new btThreadSupportPosix( info );
  289. }
  290. #endif // BT_THREADSAFE && !defined( _WIN32 )