btThreadSupportPosix.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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 btMax(1u, btMin(BT_MAX_THREAD_COUNT, std::thread::hardware_concurrency()));
  39. }
  40. #else
  41. int btGetNumHardwareThreads()
  42. {
  43. return btMax(1, 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. btCriticalSection* m_cs;
  61. // this is a copy of m_mainSemaphore,
  62. //each tread will signal once it is finished with its work
  63. sem_t* m_mainSemaphore;
  64. unsigned long threadUsed;
  65. };
  66. private:
  67. typedef unsigned long long UINT64;
  68. btAlignedObjectArray<btThreadStatus> m_activeThreadStatus;
  69. // m_mainSemaphoresemaphore will signal, if and how many threads are finished with their work
  70. sem_t* m_mainSemaphore;
  71. int m_numThreads;
  72. UINT64 m_startedThreadsMask;
  73. void startThreads(const ConstructionInfo& threadInfo);
  74. void stopThreads();
  75. int waitForResponse();
  76. btCriticalSection* m_cs;
  77. public:
  78. btThreadSupportPosix(const ConstructionInfo& threadConstructionInfo);
  79. virtual ~btThreadSupportPosix();
  80. virtual int getNumWorkerThreads() const BT_OVERRIDE { return m_numThreads; }
  81. // TODO: return the number of logical processors sharing the first L3 cache
  82. virtual int getCacheFriendlyNumThreads() const BT_OVERRIDE { return m_numThreads + 1; }
  83. // TODO: detect if CPU has hyperthreading enabled
  84. virtual int getLogicalToPhysicalCoreRatio() const BT_OVERRIDE { return 1; }
  85. virtual void runTask(int threadIndex, void* userData) BT_OVERRIDE;
  86. virtual void waitForAllTasks() BT_OVERRIDE;
  87. virtual btCriticalSection* createCriticalSection() BT_OVERRIDE;
  88. virtual void deleteCriticalSection(btCriticalSection* criticalSection) BT_OVERRIDE;
  89. };
  90. #define checkPThreadFunction(returnValue) \
  91. if (0 != returnValue) \
  92. { \
  93. printf("PThread problem at line %i in file %s: %i %d\n", __LINE__, __FILE__, returnValue, errno); \
  94. }
  95. // The number of threads should be equal to the number of available cores
  96. // Todo: each worker should be linked to a single core, using SetThreadIdealProcessor.
  97. btThreadSupportPosix::btThreadSupportPosix(const ConstructionInfo& threadConstructionInfo)
  98. {
  99. m_cs = createCriticalSection();
  100. startThreads(threadConstructionInfo);
  101. }
  102. // cleanup/shutdown Libspe2
  103. btThreadSupportPosix::~btThreadSupportPosix()
  104. {
  105. stopThreads();
  106. deleteCriticalSection(m_cs);
  107. m_cs=0;
  108. }
  109. #if (defined(__APPLE__))
  110. #define NAMED_SEMAPHORES
  111. #endif
  112. static sem_t* createSem(const char* baseName)
  113. {
  114. static int semCount = 0;
  115. #ifdef NAMED_SEMAPHORES
  116. /// Named semaphore begin
  117. char name[32];
  118. snprintf(name, 32, "/%8.s-%4.d-%4.4d", baseName, getpid(), semCount++);
  119. sem_t* tempSem = sem_open(name, O_CREAT, 0600, 0);
  120. if (tempSem != reinterpret_cast<sem_t*>(SEM_FAILED))
  121. {
  122. // printf("Created \"%s\" Semaphore %p\n", name, tempSem);
  123. }
  124. else
  125. {
  126. //printf("Error creating Semaphore %d\n", errno);
  127. exit(-1);
  128. }
  129. /// Named semaphore end
  130. #else
  131. sem_t* tempSem = new sem_t;
  132. checkPThreadFunction(sem_init(tempSem, 0, 0));
  133. #endif
  134. return tempSem;
  135. }
  136. static void destroySem(sem_t* semaphore)
  137. {
  138. #ifdef NAMED_SEMAPHORES
  139. checkPThreadFunction(sem_close(semaphore));
  140. #else
  141. checkPThreadFunction(sem_destroy(semaphore));
  142. delete semaphore;
  143. #endif
  144. }
  145. static void* threadFunction(void* argument)
  146. {
  147. btThreadSupportPosix::btThreadStatus* status = (btThreadSupportPosix::btThreadStatus*)argument;
  148. while (1)
  149. {
  150. checkPThreadFunction(sem_wait(status->startSemaphore));
  151. void* userPtr = status->m_userPtr;
  152. if (userPtr)
  153. {
  154. btAssert(status->m_status);
  155. status->m_userThreadFunc(userPtr);
  156. status->m_cs->lock();
  157. status->m_status = 2;
  158. status->m_cs->unlock();
  159. checkPThreadFunction(sem_post(status->m_mainSemaphore));
  160. status->threadUsed++;
  161. }
  162. else
  163. {
  164. //exit Thread
  165. status->m_cs->lock();
  166. status->m_status = 3;
  167. status->m_cs->unlock();
  168. checkPThreadFunction(sem_post(status->m_mainSemaphore));
  169. break;
  170. }
  171. }
  172. return 0;
  173. }
  174. ///send messages to SPUs
  175. void btThreadSupportPosix::runTask(int threadIndex, void* userData)
  176. {
  177. ///we should spawn an SPU task here, and in 'waitForResponse' it should wait for response of the (one of) the first tasks that finished
  178. btThreadStatus& threadStatus = m_activeThreadStatus[threadIndex];
  179. btAssert(threadIndex >= 0);
  180. btAssert(threadIndex < m_activeThreadStatus.size());
  181. threadStatus.m_cs = m_cs;
  182. threadStatus.m_commandId = 1;
  183. threadStatus.m_status = 1;
  184. threadStatus.m_userPtr = userData;
  185. m_startedThreadsMask |= UINT64(1) << threadIndex;
  186. // fire event to start new task
  187. checkPThreadFunction(sem_post(threadStatus.startSemaphore));
  188. }
  189. ///check for messages from SPUs
  190. int btThreadSupportPosix::waitForResponse()
  191. {
  192. ///We should wait for (one of) the first tasks to finish (or other SPU messages), and report its response
  193. ///A possible response can be 'yes, SPU handled it', or 'no, please do a PPU fallback'
  194. btAssert(m_activeThreadStatus.size());
  195. // wait for any of the threads to finish
  196. checkPThreadFunction(sem_wait(m_mainSemaphore));
  197. // get at least one thread which has finished
  198. size_t last = -1;
  199. for (size_t t = 0; t < size_t(m_activeThreadStatus.size()); ++t)
  200. {
  201. m_cs->lock();
  202. bool hasFinished = (2 == m_activeThreadStatus[t].m_status);
  203. m_cs->unlock();
  204. if (hasFinished)
  205. {
  206. last = t;
  207. break;
  208. }
  209. }
  210. btThreadStatus& threadStatus = m_activeThreadStatus[last];
  211. btAssert(threadStatus.m_status > 1);
  212. threadStatus.m_status = 0;
  213. // need to find an active spu
  214. btAssert(last >= 0);
  215. m_startedThreadsMask &= ~(UINT64(1) << last);
  216. return last;
  217. }
  218. void btThreadSupportPosix::waitForAllTasks()
  219. {
  220. while (m_startedThreadsMask)
  221. {
  222. waitForResponse();
  223. }
  224. }
  225. void btThreadSupportPosix::startThreads(const ConstructionInfo& threadConstructionInfo)
  226. {
  227. m_numThreads = btGetNumHardwareThreads() - 1; // main thread exists already
  228. m_activeThreadStatus.resize(m_numThreads);
  229. m_startedThreadsMask = 0;
  230. m_mainSemaphore = createSem("main");
  231. //checkPThreadFunction(sem_wait(mainSemaphore));
  232. for (int i = 0; i < m_numThreads; i++)
  233. {
  234. btThreadStatus& threadStatus = m_activeThreadStatus[i];
  235. threadStatus.startSemaphore = createSem("threadLocal");
  236. threadStatus.m_userPtr = 0;
  237. threadStatus.m_cs = m_cs;
  238. threadStatus.m_taskId = i;
  239. threadStatus.m_commandId = 0;
  240. threadStatus.m_status = 0;
  241. threadStatus.m_mainSemaphore = m_mainSemaphore;
  242. threadStatus.m_userThreadFunc = threadConstructionInfo.m_userThreadFunc;
  243. threadStatus.threadUsed = 0;
  244. checkPThreadFunction(pthread_create(&threadStatus.thread, NULL, &threadFunction, (void*)&threadStatus));
  245. }
  246. }
  247. ///tell the task scheduler we are done with the SPU tasks
  248. void btThreadSupportPosix::stopThreads()
  249. {
  250. for (size_t t = 0; t < size_t(m_activeThreadStatus.size()); ++t)
  251. {
  252. btThreadStatus& threadStatus = m_activeThreadStatus[t];
  253. threadStatus.m_userPtr = 0;
  254. checkPThreadFunction(sem_post(threadStatus.startSemaphore));
  255. checkPThreadFunction(sem_wait(m_mainSemaphore));
  256. checkPThreadFunction(pthread_join(threadStatus.thread, 0));
  257. destroySem(threadStatus.startSemaphore);
  258. }
  259. destroySem(m_mainSemaphore);
  260. m_activeThreadStatus.clear();
  261. }
  262. class btCriticalSectionPosix : public btCriticalSection
  263. {
  264. pthread_mutex_t m_mutex;
  265. public:
  266. btCriticalSectionPosix()
  267. {
  268. pthread_mutex_init(&m_mutex, NULL);
  269. }
  270. virtual ~btCriticalSectionPosix()
  271. {
  272. pthread_mutex_destroy(&m_mutex);
  273. }
  274. virtual void lock()
  275. {
  276. pthread_mutex_lock(&m_mutex);
  277. }
  278. virtual void unlock()
  279. {
  280. pthread_mutex_unlock(&m_mutex);
  281. }
  282. };
  283. btCriticalSection* btThreadSupportPosix::createCriticalSection()
  284. {
  285. return new btCriticalSectionPosix();
  286. }
  287. void btThreadSupportPosix::deleteCriticalSection(btCriticalSection* cs)
  288. {
  289. delete cs;
  290. }
  291. btThreadSupportInterface* btThreadSupportInterface::create(const ConstructionInfo& info)
  292. {
  293. return new btThreadSupportPosix(info);
  294. }
  295. #endif // BT_THREADSAFE && !defined( _WIN32 )