The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

392 lines
12KB

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