juce_Thread.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. or without fee is hereby granted, provided that the above copyright notice and this
  7. permission notice appear in all copies.
  8. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  9. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  10. NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  11. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  12. IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. ------------------------------------------------------------------------------
  15. NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
  16. All other JUCE modules are covered by a dual GPL/commercial license, so if you are
  17. using any other modules, be sure to check that you also comply with their license.
  18. For more details, visit www.juce.com
  19. ==============================================================================
  20. */
  21. Thread::Thread (const String& threadName_, const size_t stackSize)
  22. : threadName (threadName_),
  23. threadHandle (nullptr),
  24. threadId (0),
  25. threadPriority (5),
  26. threadStackSize (stackSize),
  27. affinityMask (0),
  28. shouldExit (false)
  29. {
  30. }
  31. Thread::~Thread()
  32. {
  33. /* If your thread class's destructor has been called without first stopping the thread, that
  34. means that this partially destructed object is still performing some work - and that's
  35. probably a Bad Thing!
  36. To avoid this type of nastiness, always make sure you call stopThread() before or during
  37. your subclass's destructor.
  38. */
  39. jassert (! isThreadRunning());
  40. stopThread (-1);
  41. }
  42. //==============================================================================
  43. // Use a ref-counted object to hold this shared data, so that it can outlive its static
  44. // shared pointer when threads are still running during static shutdown.
  45. struct CurrentThreadHolder : public ReferenceCountedObject
  46. {
  47. CurrentThreadHolder() noexcept {}
  48. typedef ReferenceCountedObjectPtr<CurrentThreadHolder> Ptr;
  49. ThreadLocalValue<Thread*> value;
  50. JUCE_DECLARE_NON_COPYABLE (CurrentThreadHolder)
  51. };
  52. static char currentThreadHolderLock [sizeof (SpinLock)]; // (statically initialised to zeros).
  53. static SpinLock* castToSpinLockWithoutAliasingWarning (void* s)
  54. {
  55. return static_cast<SpinLock*> (s);
  56. }
  57. static CurrentThreadHolder::Ptr getCurrentThreadHolder()
  58. {
  59. static CurrentThreadHolder::Ptr currentThreadHolder;
  60. SpinLock::ScopedLockType lock (*castToSpinLockWithoutAliasingWarning (currentThreadHolderLock));
  61. if (currentThreadHolder == nullptr)
  62. currentThreadHolder = new CurrentThreadHolder();
  63. return currentThreadHolder;
  64. }
  65. void Thread::threadEntryPoint()
  66. {
  67. const CurrentThreadHolder::Ptr currentThreadHolder (getCurrentThreadHolder());
  68. currentThreadHolder->value = this;
  69. if (threadName.isNotEmpty())
  70. setCurrentThreadName (threadName);
  71. if (startSuspensionEvent.wait (10000))
  72. {
  73. jassert (getCurrentThreadId() == threadId);
  74. if (affinityMask != 0)
  75. setCurrentThreadAffinityMask (affinityMask);
  76. try
  77. {
  78. run();
  79. }
  80. catch (...)
  81. {
  82. jassertfalse; // Your run() method mustn't throw any exceptions!
  83. }
  84. }
  85. currentThreadHolder->value.releaseCurrentThreadStorage();
  86. closeThreadHandle();
  87. }
  88. // used to wrap the incoming call from the platform-specific code
  89. void JUCE_API juce_threadEntryPoint (void* userData)
  90. {
  91. static_cast<Thread*> (userData)->threadEntryPoint();
  92. }
  93. //==============================================================================
  94. void Thread::startThread()
  95. {
  96. const ScopedLock sl (startStopLock);
  97. shouldExit = false;
  98. if (threadHandle == nullptr)
  99. {
  100. launchThread();
  101. setThreadPriority (threadHandle, threadPriority);
  102. startSuspensionEvent.signal();
  103. }
  104. }
  105. void Thread::startThread (const int priority)
  106. {
  107. const ScopedLock sl (startStopLock);
  108. if (threadHandle == nullptr)
  109. {
  110. threadPriority = priority;
  111. startThread();
  112. }
  113. else
  114. {
  115. setPriority (priority);
  116. }
  117. }
  118. bool Thread::isThreadRunning() const
  119. {
  120. return threadHandle != nullptr;
  121. }
  122. Thread* JUCE_CALLTYPE Thread::getCurrentThread()
  123. {
  124. return getCurrentThreadHolder()->value.get();
  125. }
  126. //==============================================================================
  127. void Thread::signalThreadShouldExit()
  128. {
  129. shouldExit = true;
  130. }
  131. bool Thread::currentThreadShouldExit()
  132. {
  133. if (Thread* currentThread = getCurrentThread())
  134. return currentThread->threadShouldExit();
  135. return false;
  136. }
  137. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  138. {
  139. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  140. jassert (getThreadId() != getCurrentThreadId() || getCurrentThreadId() == 0);
  141. const uint32 timeoutEnd = Time::getMillisecondCounter() + (uint32) timeOutMilliseconds;
  142. while (isThreadRunning())
  143. {
  144. if (timeOutMilliseconds >= 0 && Time::getMillisecondCounter() > timeoutEnd)
  145. return false;
  146. sleep (2);
  147. }
  148. return true;
  149. }
  150. bool Thread::stopThread (const int timeOutMilliseconds)
  151. {
  152. // agh! You can't stop the thread that's calling this method! How on earth
  153. // would that work??
  154. jassert (getCurrentThreadId() != getThreadId());
  155. const ScopedLock sl (startStopLock);
  156. if (isThreadRunning())
  157. {
  158. signalThreadShouldExit();
  159. notify();
  160. if (timeOutMilliseconds != 0)
  161. waitForThreadToExit (timeOutMilliseconds);
  162. if (isThreadRunning())
  163. {
  164. // very bad karma if this point is reached, as there are bound to be
  165. // locks and events left in silly states when a thread is killed by force..
  166. jassertfalse;
  167. Logger::writeToLog ("!! killing thread by force !!");
  168. killThread();
  169. threadHandle = nullptr;
  170. threadId = 0;
  171. return false;
  172. }
  173. }
  174. return true;
  175. }
  176. //==============================================================================
  177. bool Thread::setPriority (const int newPriority)
  178. {
  179. // NB: deadlock possible if you try to set the thread prio from the thread itself,
  180. // so using setCurrentThreadPriority instead in that case.
  181. if (getCurrentThreadId() == getThreadId())
  182. return setCurrentThreadPriority (newPriority);
  183. const ScopedLock sl (startStopLock);
  184. if ((! isThreadRunning()) || setThreadPriority (threadHandle, newPriority))
  185. {
  186. threadPriority = newPriority;
  187. return true;
  188. }
  189. return false;
  190. }
  191. bool Thread::setCurrentThreadPriority (const int newPriority)
  192. {
  193. return setThreadPriority (0, newPriority);
  194. }
  195. void Thread::setAffinityMask (const uint32 newAffinityMask)
  196. {
  197. affinityMask = newAffinityMask;
  198. }
  199. //==============================================================================
  200. bool Thread::wait (const int timeOutMilliseconds) const
  201. {
  202. return defaultEvent.wait (timeOutMilliseconds);
  203. }
  204. void Thread::notify() const
  205. {
  206. defaultEvent.signal();
  207. }
  208. //==============================================================================
  209. void SpinLock::enter() const noexcept
  210. {
  211. if (! tryEnter())
  212. {
  213. for (int i = 20; --i >= 0;)
  214. if (tryEnter())
  215. return;
  216. while (! tryEnter())
  217. Thread::yield();
  218. }
  219. }
  220. //==============================================================================
  221. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() noexcept
  222. {
  223. return juce_isRunningUnderDebugger();
  224. }
  225. //==============================================================================
  226. #if JUCE_UNIT_TESTS
  227. class AtomicTests : public UnitTest
  228. {
  229. public:
  230. AtomicTests() : UnitTest ("Atomics") {}
  231. void runTest() override
  232. {
  233. beginTest ("Misc");
  234. char a1[7];
  235. expect (numElementsInArray(a1) == 7);
  236. int a2[3];
  237. expect (numElementsInArray(a2) == 3);
  238. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  239. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  240. expect (ByteOrder::swap ((uint64) 0x1122334455667788ULL) == 0x8877665544332211LL);
  241. beginTest ("Atomic int");
  242. AtomicTester <int>::testInteger (*this);
  243. beginTest ("Atomic unsigned int");
  244. AtomicTester <unsigned int>::testInteger (*this);
  245. beginTest ("Atomic int32");
  246. AtomicTester <int32>::testInteger (*this);
  247. beginTest ("Atomic uint32");
  248. AtomicTester <uint32>::testInteger (*this);
  249. beginTest ("Atomic long");
  250. AtomicTester <long>::testInteger (*this);
  251. beginTest ("Atomic void*");
  252. AtomicTester <void*>::testInteger (*this);
  253. beginTest ("Atomic int*");
  254. AtomicTester <int*>::testInteger (*this);
  255. beginTest ("Atomic float");
  256. AtomicTester <float>::testFloat (*this);
  257. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  258. beginTest ("Atomic int64");
  259. AtomicTester <int64>::testInteger (*this);
  260. beginTest ("Atomic uint64");
  261. AtomicTester <uint64>::testInteger (*this);
  262. beginTest ("Atomic double");
  263. AtomicTester <double>::testFloat (*this);
  264. #endif
  265. }
  266. template <typename Type>
  267. class AtomicTester
  268. {
  269. public:
  270. AtomicTester() {}
  271. static void testInteger (UnitTest& test)
  272. {
  273. Atomic<Type> a, b;
  274. a.set ((Type) 10);
  275. test.expect (a.value == (Type) 10);
  276. test.expect (a.get() == (Type) 10);
  277. a += (Type) 15;
  278. test.expect (a.get() == (Type) 25);
  279. a.memoryBarrier();
  280. a -= (Type) 5;
  281. test.expect (a.get() == (Type) 20);
  282. test.expect (++a == (Type) 21);
  283. ++a;
  284. test.expect (--a == (Type) 21);
  285. test.expect (a.get() == (Type) 21);
  286. a.memoryBarrier();
  287. testFloat (test);
  288. }
  289. static void testFloat (UnitTest& test)
  290. {
  291. Atomic<Type> a, b;
  292. a = (Type) 21;
  293. a.memoryBarrier();
  294. /* These are some simple test cases to check the atomics - let me know
  295. if any of these assertions fail on your system!
  296. */
  297. test.expect (a.get() == (Type) 21);
  298. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  299. test.expect (a.get() == (Type) 21);
  300. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  301. test.expect (a.get() == (Type) 101);
  302. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  303. test.expect (a.get() == (Type) 101);
  304. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  305. test.expect (a.get() == (Type) 200);
  306. test.expect (a.exchange ((Type) 300) == (Type) 200);
  307. test.expect (a.get() == (Type) 300);
  308. b = a;
  309. test.expect (b.get() == a.get());
  310. }
  311. };
  312. };
  313. static AtomicTests atomicUnitTests;
  314. #endif