testThreading.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "platform/threads/thread.h"
  24. #include "platform/threads/semaphore.h"
  25. #include "platform/threads/mutex.h"
  26. #include "unit/test.h"
  27. #include "core/util/tVector.h"
  28. #include "console/console.h"
  29. using namespace UnitTesting;
  30. class ThreadTestHarness
  31. {
  32. U32 mStartTime, mEndTime, mCleanupTime;
  33. void (*mThreadBody)(void*);
  34. S32 mThreadCount;
  35. Thread **mThreads;
  36. public:
  37. ThreadTestHarness()
  38. {
  39. mStartTime = mEndTime = mCleanupTime = 0;
  40. mThreadBody = NULL;
  41. mThreadCount = 1;
  42. mThreads = NULL;
  43. }
  44. void startThreads(void (*threadBody)(void*), void *arg, U32 threadCount)
  45. {
  46. mThreadCount = threadCount;
  47. mThreadBody = threadBody;
  48. // Start up threadCount threads...
  49. mThreads = new Thread*[threadCount];
  50. mStartTime = Platform::getRealMilliseconds();
  51. //Con::printf(" Running with %d threads...", threadCount);
  52. for(S32 i=0; i<mThreadCount; i++)
  53. {
  54. mThreads[i] = new Thread(threadBody, arg);
  55. mThreads[i]->start();
  56. }
  57. }
  58. void waitForThreadExit(U32 checkFrequencyMs)
  59. {
  60. // And wait for them to complete.
  61. bool someAlive = true;
  62. S32 liveCount = mThreadCount;
  63. while(someAlive)
  64. {
  65. //Con::printf(" - Sleeping for %dms with %d live threads.", checkFrequencyMs, liveCount);
  66. Platform::sleep(checkFrequencyMs);
  67. someAlive = false;
  68. liveCount = 0;
  69. for(S32 i=0; i<mThreadCount; i++)
  70. {
  71. if(!mThreads[i]->isAlive())
  72. continue;
  73. someAlive = true;
  74. liveCount++;
  75. }
  76. }
  77. mEndTime = Platform::getRealMilliseconds();
  78. // Clean up memory at this point.
  79. for(S32 i=0; i<mThreadCount; i++)
  80. delete mThreads[i];
  81. delete[] mThreads;
  82. // Make sure we didn't take a long time to complete.
  83. mCleanupTime = Platform::getRealMilliseconds();
  84. // And dump some stats.
  85. Con::printf(" Took approximately %dms (+/- %dms) to run %d threads, and %dms to cleanup.",
  86. (mEndTime - mStartTime),
  87. checkFrequencyMs,
  88. mThreadCount,
  89. mCleanupTime - mEndTime);
  90. }
  91. };
  92. CreateUnitTest( ThreadSanityCheck, "Platform/Threads/BasicSanity")
  93. {
  94. const static S32 amountOfWork = 100;
  95. const static S32 numberOfThreads = 8;
  96. static void threadBody(void *)
  97. {
  98. S32 work = 0x381f4fd3;
  99. // Spin on some work, then exit.
  100. for(S32 i=0; i<amountOfWork; i++)
  101. {
  102. // Do a little computation...
  103. work ^= (i + work | amountOfWork);
  104. // And sleep a slightly variable bit.
  105. Platform::sleep(10 + ((work+i) % 10));
  106. }
  107. }
  108. void runNThreads(S32 threadCount)
  109. {
  110. ThreadTestHarness tth;
  111. tth.startThreads(&threadBody, NULL, threadCount);
  112. tth.waitForThreadExit(32);
  113. }
  114. void run()
  115. {
  116. for(S32 i=0; i<numberOfThreads; i++)
  117. runNThreads(i);
  118. }
  119. };
  120. CreateUnitTest( MutexStressTest, "Platform/Threads/MutexStress")
  121. {
  122. const static S32 numberOfLocks = 100;
  123. const static S32 numberOfThreads = 4;
  124. void *mMutex;
  125. static void threadBody(void *mutex)
  126. {
  127. // Acquire the mutex numberOfLocks times. Sleep for 1ms, acquire, sleep, release.
  128. S32 lockCount = numberOfLocks;
  129. while(lockCount--)
  130. {
  131. Platform::sleep(1);
  132. Mutex::lockMutex(mutex, true);
  133. Platform::sleep(1);
  134. Mutex::unlockMutex(mutex);
  135. }
  136. }
  137. void runNThreads(S32 threadCount)
  138. {
  139. ThreadTestHarness tth;
  140. mMutex = Mutex::createMutex();
  141. tth.startThreads(&threadBody, mMutex, threadCount);
  142. // We fudge the wait period to be about the expected time assuming
  143. // perfect execution speed.
  144. tth.waitForThreadExit(32); //threadCount * 2 * numberOfLocks + 100);
  145. Mutex::destroyMutex(mMutex);
  146. }
  147. void run()
  148. {
  149. for(S32 i=0; i<numberOfThreads; i++)
  150. runNThreads(i);
  151. }
  152. };
  153. CreateUnitTest( MemoryStressTest, "Platform/Threads/MemoryStress")
  154. {
  155. const static S32 numberOfAllocs = 1000;
  156. const static S32 minAllocSize = 13;
  157. const static S32 maxAllocSize = 1024 * 1024;
  158. const static S32 numberOfThreads = 4;
  159. void *mMutex;
  160. // Cheap little RNG so we can vary our allocations more uniquely per thread.
  161. static U32 threadRandom(U32 &seed, U32 min, U32 max)
  162. {
  163. seed = (1664525 * seed + 1013904223);
  164. U32 res = seed;
  165. res %= (max - min);
  166. return res + min;
  167. }
  168. static void threadBody(void *mutex)
  169. {
  170. // Acquire the mutex numberOfLocks times. Sleep for 1ms, acquire, sleep, release.
  171. S32 allocCount = numberOfAllocs;
  172. U32 seed = (U32)((U32)mutex + (U32)&allocCount);
  173. while(allocCount--)
  174. {
  175. U8 *mem = new U8[threadRandom(seed, minAllocSize, maxAllocSize)];
  176. delete[] mem;
  177. }
  178. }
  179. void runNThreads(S32 threadCount)
  180. {
  181. ThreadTestHarness tth;
  182. mMutex = Mutex::createMutex();
  183. tth.startThreads(&threadBody, mMutex, threadCount);
  184. // We fudge the wait period to be about the expected time assuming
  185. // perfect execution speed.
  186. tth.waitForThreadExit(32);
  187. Mutex::destroyMutex(mMutex);
  188. }
  189. void run()
  190. {
  191. for(S32 i=0; i<numberOfThreads; i++)
  192. runNThreads(i);
  193. }
  194. };
  195. CreateUnitTest( ThreadGymnastics, "Platform/Threads/BasicSynchronization")
  196. {
  197. void run()
  198. {
  199. // We test various scenarios wrt to locking and unlocking, in a single
  200. // thread, just to make sure our basic primitives are working in the
  201. // most basic case.
  202. void *mutex1 = Mutex::createMutex();
  203. test(mutex1, "First Mutex::createMutex call failed - that's pretty bad!");
  204. void *mutex2 = Mutex::createMutex();
  205. test(mutex2, "Second Mutex::createMutex call failed - that's pretty bad, too!");
  206. test(Mutex::lockMutex(mutex1, false), "Nonblocking call to brand new mutex failed - should not be.");
  207. test(Mutex::lockMutex(mutex1, true), "Failed relocking a mutex from the same thread - should be able to do this.");
  208. // Unlock & kill mutex 1
  209. Mutex::unlockMutex(mutex1);
  210. Mutex::unlockMutex(mutex1);
  211. Mutex::destroyMutex(mutex1);
  212. // Kill mutex2, which was never touched.
  213. Mutex::destroyMutex(mutex2);
  214. // Now we can test semaphores.
  215. Semaphore *sem1 = new Semaphore(1);
  216. Semaphore *sem2 = new Semaphore(1);
  217. // Test that we can do non-blocking acquires that succeed.
  218. test(sem1->acquire(false), "Should succeed at acquiring a new semaphore with count 1.");
  219. test(sem2->acquire(false), "This one should succeed too, see previous test.");
  220. // Test that we can do non-blocking acquires that fail.
  221. test(sem1->acquire(false)==false, "Should failed, as we've already got the sem.");
  222. sem1->release();
  223. test(sem2->acquire(false)==false, "Should also fail.");
  224. sem2->release();
  225. // Test that we can do blocking acquires that succeed.
  226. test(sem1->acquire(true)==true, "Should succeed as we just released.");
  227. test(sem2->acquire(true)==true, "Should succeed as we just released.");
  228. // Can't test blocking acquires that never happen... :)
  229. // Clean up.
  230. delete sem1;
  231. delete sem2;
  232. }
  233. };
  234. CreateUnitTest( SemaphoreWaitTest, "Platform/Threads/SemaphoreWaitTest")
  235. {
  236. static void threadBody(void *self)
  237. {
  238. SemaphoreWaitTest *me = (SemaphoreWaitTest*)self;
  239. // Wait for the semaphore to get released.
  240. me->mSemaphore->acquire();
  241. // Increment the counter.
  242. Mutex::lockMutex(me->mMutex);
  243. me->mDoneCount++;
  244. Mutex::unlockMutex(me->mMutex);
  245. // Signal back to the main thread we're done.
  246. me->mPostbackSemaphore->release();
  247. }
  248. Semaphore *mSemaphore;
  249. Semaphore *mPostbackSemaphore;
  250. void *mMutex;
  251. U32 mDoneCount;
  252. const static S32 csmThreadCount = 10;
  253. void run()
  254. {
  255. ThreadTestHarness tth;
  256. mDoneCount = 0;
  257. mSemaphore = new Semaphore(0);
  258. mPostbackSemaphore = new Semaphore(0);
  259. mMutex = Mutex::createMutex();
  260. tth.startThreads(&threadBody, this, csmThreadCount);
  261. Platform::sleep(500);
  262. Mutex::lockMutex(mMutex);
  263. test(mDoneCount == 0, "no threads should have touched the counter yet.");
  264. Mutex::unlockMutex(mMutex);
  265. // Let 500 come out.
  266. for(S32 i=0; i<csmThreadCount/2; i++)
  267. mSemaphore->release();
  268. // And wait for 500 postbacks.
  269. for(S32 i=0; i<csmThreadCount/2; i++)
  270. mPostbackSemaphore->acquire();
  271. Mutex::lockMutex(mMutex);
  272. test(mDoneCount == csmThreadCount / 2, "Didn't get expected number of done threads! (a)");
  273. Mutex::unlockMutex(mMutex);
  274. // Ok, now do the rest.
  275. // Let 500 come out.
  276. for(S32 i=0; i<csmThreadCount/2; i++)
  277. mSemaphore->release();
  278. // And wait for 500 postbacks.
  279. for(S32 i=0; i<csmThreadCount/2; i++)
  280. mPostbackSemaphore->acquire();
  281. Mutex::lockMutex(mMutex);
  282. test(mDoneCount == csmThreadCount, "Didn't get expected number of done threads! (b)");
  283. Mutex::unlockMutex(mMutex);
  284. // Wait for the threads to exit - shouldn't have to wait ever though.
  285. tth.waitForThreadExit(10);
  286. // Make sure no one touched our data after shutdown time.
  287. Mutex::lockMutex(mMutex);
  288. test(mDoneCount == csmThreadCount, "Didn't get expected number of done threads! (c)");
  289. Mutex::unlockMutex(mMutex);
  290. }
  291. };
  292. CreateUnitTest( MutexWaitTest, "Platform/Threads/MutexWaitTest")
  293. {
  294. static void threadBody(void *self)
  295. {
  296. MutexWaitTest *me = (MutexWaitTest*)self;
  297. // Increment the counter. We'll block until the mutex
  298. // is open.
  299. Mutex::lockMutex(me->mMutex);
  300. me->mDoneCount++;
  301. Mutex::unlockMutex(me->mMutex);
  302. }
  303. void *mMutex;
  304. U32 mDoneCount;
  305. const static S32 csmThreadCount = 10;
  306. void run()
  307. {
  308. mMutex = Mutex::createMutex();
  309. mDoneCount = 0;
  310. // We lock the mutex before we create any threads, so that all the threads
  311. // block on the mutex. Then we unlock it and let them all work their way
  312. // through the increment.
  313. Mutex::lockMutex(mMutex);
  314. ThreadTestHarness tth;
  315. tth.startThreads(&threadBody, this, csmThreadCount);
  316. Platform::sleep(5000);
  317. // Check count is still zero.
  318. test(mDoneCount == 0, "Uh oh - a thread somehow didn't get blocked by the locked mutex!");
  319. // Open the flood gates...
  320. Mutex::unlockMutex(mMutex);
  321. // Wait for the threads to all finish executing.
  322. tth.waitForThreadExit(10);
  323. Mutex::lockMutex(mMutex);
  324. test(mDoneCount == csmThreadCount, "Hmm - all threads reported done, but we didn't get the expected count.");
  325. Mutex::unlockMutex(mMutex);
  326. // Kill the mutex.
  327. Mutex::destroyMutex(mMutex);
  328. }
  329. };