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.

405 lines
11KB

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