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.

537 lines
15KB

  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. namespace juce
  18. {
  19. Thread::Thread (const String& name, size_t stackSize)
  20. : threadName (name), threadStackSize (stackSize)
  21. {
  22. }
  23. Thread::~Thread()
  24. {
  25. if (deleteOnThreadEnd)
  26. return;
  27. /* If your thread class's destructor has been called without first stopping the thread, that
  28. means that this partially destructed object is still performing some work - and that's
  29. probably a Bad Thing!
  30. To avoid this type of nastiness, always make sure you call stopThread() before or during
  31. your subclass's destructor.
  32. */
  33. jassert (! isThreadRunning());
  34. stopThread (-1);
  35. }
  36. //==============================================================================
  37. // Use a ref-counted object to hold this shared data, so that it can outlive its static
  38. // shared pointer when threads are still running during static shutdown.
  39. struct CurrentThreadHolder : public ReferenceCountedObject
  40. {
  41. CurrentThreadHolder() noexcept {}
  42. using Ptr = ReferenceCountedObjectPtr<CurrentThreadHolder>;
  43. ThreadLocalValue<Thread*> value;
  44. JUCE_DECLARE_NON_COPYABLE (CurrentThreadHolder)
  45. };
  46. static char currentThreadHolderLock [sizeof (SpinLock)]; // (statically initialised to zeros).
  47. static SpinLock* castToSpinLockWithoutAliasingWarning (void* s)
  48. {
  49. return static_cast<SpinLock*> (s);
  50. }
  51. static CurrentThreadHolder::Ptr getCurrentThreadHolder()
  52. {
  53. static CurrentThreadHolder::Ptr currentThreadHolder;
  54. SpinLock::ScopedLockType lock (*castToSpinLockWithoutAliasingWarning (currentThreadHolderLock));
  55. if (currentThreadHolder == nullptr)
  56. currentThreadHolder = new CurrentThreadHolder();
  57. return currentThreadHolder;
  58. }
  59. void Thread::threadEntryPoint()
  60. {
  61. const CurrentThreadHolder::Ptr currentThreadHolder (getCurrentThreadHolder());
  62. currentThreadHolder->value = this;
  63. if (threadName.isNotEmpty())
  64. setCurrentThreadName (threadName);
  65. if (startSuspensionEvent.wait (10000))
  66. {
  67. jassert (getCurrentThreadId() == threadId.get());
  68. if (affinityMask != 0)
  69. setCurrentThreadAffinityMask (affinityMask);
  70. try
  71. {
  72. run();
  73. }
  74. catch (...)
  75. {
  76. jassertfalse; // Your run() method mustn't throw any exceptions!
  77. }
  78. }
  79. currentThreadHolder->value.releaseCurrentThreadStorage();
  80. // Once closeThreadHandle is called this class may be deleted by a different
  81. // thread, so we need to store deleteOnThreadEnd in a local variable.
  82. auto shouldDeleteThis = deleteOnThreadEnd;
  83. closeThreadHandle();
  84. if (shouldDeleteThis)
  85. delete this;
  86. }
  87. // used to wrap the incoming call from the platform-specific code
  88. void JUCE_API juce_threadEntryPoint (void* userData)
  89. {
  90. static_cast<Thread*> (userData)->threadEntryPoint();
  91. }
  92. //==============================================================================
  93. void Thread::startThread()
  94. {
  95. const ScopedLock sl (startStopLock);
  96. shouldExit = 0;
  97. if (threadHandle.get() == nullptr)
  98. {
  99. launchThread();
  100. setThreadPriority (threadHandle.get(), threadPriority);
  101. startSuspensionEvent.signal();
  102. }
  103. }
  104. void Thread::startThread (int priority)
  105. {
  106. const ScopedLock sl (startStopLock);
  107. if (threadHandle.get() == nullptr)
  108. {
  109. auto isRealtime = (priority == realtimeAudioPriority);
  110. #if JUCE_ANDROID
  111. isAndroidRealtimeThread = isRealtime;
  112. #endif
  113. if (isRealtime)
  114. priority = 9;
  115. threadPriority = priority;
  116. startThread();
  117. }
  118. else
  119. {
  120. setPriority (priority);
  121. }
  122. }
  123. bool Thread::isThreadRunning() const
  124. {
  125. return threadHandle.get() != nullptr;
  126. }
  127. Thread* JUCE_CALLTYPE Thread::getCurrentThread()
  128. {
  129. return getCurrentThreadHolder()->value.get();
  130. }
  131. Thread::ThreadID Thread::getThreadId() const noexcept
  132. {
  133. return threadId.get();
  134. }
  135. //==============================================================================
  136. void Thread::signalThreadShouldExit()
  137. {
  138. shouldExit = 1;
  139. listeners.call ([] (Listener& l) { l.exitSignalSent(); });
  140. }
  141. bool Thread::threadShouldExit() const
  142. {
  143. return shouldExit.get() != 0;
  144. }
  145. bool Thread::currentThreadShouldExit()
  146. {
  147. if (auto* currentThread = getCurrentThread())
  148. return currentThread->threadShouldExit();
  149. return false;
  150. }
  151. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  152. {
  153. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  154. jassert (getThreadId() != getCurrentThreadId() || getCurrentThreadId() == 0);
  155. auto timeoutEnd = Time::getMillisecondCounter() + (uint32) timeOutMilliseconds;
  156. while (isThreadRunning())
  157. {
  158. if (timeOutMilliseconds >= 0 && Time::getMillisecondCounter() > timeoutEnd)
  159. return false;
  160. sleep (2);
  161. }
  162. return true;
  163. }
  164. bool Thread::stopThread (const int timeOutMilliseconds)
  165. {
  166. // agh! You can't stop the thread that's calling this method! How on earth
  167. // would that work??
  168. jassert (getCurrentThreadId() != getThreadId());
  169. const ScopedLock sl (startStopLock);
  170. if (isThreadRunning())
  171. {
  172. signalThreadShouldExit();
  173. notify();
  174. if (timeOutMilliseconds != 0)
  175. waitForThreadToExit (timeOutMilliseconds);
  176. if (isThreadRunning())
  177. {
  178. // very bad karma if this point is reached, as there are bound to be
  179. // locks and events left in silly states when a thread is killed by force..
  180. jassertfalse;
  181. Logger::writeToLog ("!! killing thread by force !!");
  182. killThread();
  183. threadHandle = nullptr;
  184. threadId = 0;
  185. return false;
  186. }
  187. }
  188. return true;
  189. }
  190. void Thread::addListener (Listener* listener)
  191. {
  192. listeners.add (listener);
  193. }
  194. void Thread::removeListener (Listener* listener)
  195. {
  196. listeners.remove (listener);
  197. }
  198. //==============================================================================
  199. bool Thread::setPriority (int newPriority)
  200. {
  201. bool isRealtime = (newPriority == realtimeAudioPriority);
  202. if (isRealtime)
  203. newPriority = 9;
  204. // NB: deadlock possible if you try to set the thread prio from the thread itself,
  205. // so using setCurrentThreadPriority instead in that case.
  206. if (getCurrentThreadId() == getThreadId())
  207. return setCurrentThreadPriority (newPriority);
  208. const ScopedLock sl (startStopLock);
  209. #if JUCE_ANDROID
  210. // you cannot switch from or to an Android realtime thread once the
  211. // thread is already running!
  212. jassert (isThreadRunning() && (isRealtime == isAndroidRealtimeThread));
  213. isAndroidRealtimeThread = isRealtime;
  214. #endif
  215. if ((! isThreadRunning()) || setThreadPriority (threadHandle.get(), newPriority))
  216. {
  217. threadPriority = newPriority;
  218. return true;
  219. }
  220. return false;
  221. }
  222. bool Thread::setCurrentThreadPriority (const int newPriority)
  223. {
  224. return setThreadPriority (0, newPriority);
  225. }
  226. void Thread::setAffinityMask (const uint32 newAffinityMask)
  227. {
  228. affinityMask = newAffinityMask;
  229. }
  230. //==============================================================================
  231. bool Thread::wait (const int timeOutMilliseconds) const
  232. {
  233. return defaultEvent.wait (timeOutMilliseconds);
  234. }
  235. void Thread::notify() const
  236. {
  237. defaultEvent.signal();
  238. }
  239. //==============================================================================
  240. struct LambdaThread : public Thread
  241. {
  242. LambdaThread (std::function<void()> f) : Thread ("anonymous"), fn (f) {}
  243. void run() override
  244. {
  245. fn();
  246. fn = {}; // free any objects that the lambda might contain while the thread is still active
  247. }
  248. std::function<void()> fn;
  249. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LambdaThread)
  250. };
  251. void Thread::launch (std::function<void()> functionToRun)
  252. {
  253. auto anon = new LambdaThread (functionToRun);
  254. anon->deleteOnThreadEnd = true;
  255. anon->startThread();
  256. }
  257. //==============================================================================
  258. void SpinLock::enter() const noexcept
  259. {
  260. if (! tryEnter())
  261. {
  262. for (int i = 20; --i >= 0;)
  263. if (tryEnter())
  264. return;
  265. while (! tryEnter())
  266. Thread::yield();
  267. }
  268. }
  269. //==============================================================================
  270. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() noexcept
  271. {
  272. return juce_isRunningUnderDebugger();
  273. }
  274. #if JUCE_UNIT_TESTS
  275. //==============================================================================
  276. class AtomicTests : public UnitTest
  277. {
  278. public:
  279. AtomicTests() : UnitTest ("Atomics", "Threads") {}
  280. void runTest() override
  281. {
  282. beginTest ("Misc");
  283. char a1[7];
  284. expect (numElementsInArray(a1) == 7);
  285. int a2[3];
  286. expect (numElementsInArray(a2) == 3);
  287. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  288. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  289. expect (ByteOrder::swap ((uint64) 0x1122334455667788ULL) == 0x8877665544332211LL);
  290. beginTest ("Atomic int");
  291. AtomicTester <int>::testInteger (*this);
  292. beginTest ("Atomic unsigned int");
  293. AtomicTester <unsigned int>::testInteger (*this);
  294. beginTest ("Atomic int32");
  295. AtomicTester <int32>::testInteger (*this);
  296. beginTest ("Atomic uint32");
  297. AtomicTester <uint32>::testInteger (*this);
  298. beginTest ("Atomic long");
  299. AtomicTester <long>::testInteger (*this);
  300. beginTest ("Atomic int*");
  301. AtomicTester <int*>::testInteger (*this);
  302. beginTest ("Atomic float");
  303. AtomicTester <float>::testFloat (*this);
  304. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  305. beginTest ("Atomic int64");
  306. AtomicTester <int64>::testInteger (*this);
  307. beginTest ("Atomic uint64");
  308. AtomicTester <uint64>::testInteger (*this);
  309. beginTest ("Atomic double");
  310. AtomicTester <double>::testFloat (*this);
  311. #endif
  312. beginTest ("Atomic pointer increment/decrement");
  313. Atomic<int*> a (a2); int* b (a2);
  314. expect (++a == ++b);
  315. {
  316. beginTest ("Atomic void*");
  317. Atomic<void*> atomic;
  318. void* c;
  319. atomic.set ((void*) 10);
  320. c = (void*) 10;
  321. expect (atomic.value == c);
  322. expect (atomic.get() == c);
  323. }
  324. }
  325. template <typename Type>
  326. class AtomicTester
  327. {
  328. public:
  329. AtomicTester() {}
  330. static void testInteger (UnitTest& test)
  331. {
  332. Atomic<Type> a, b;
  333. Type c;
  334. a.set ((Type) 10);
  335. c = (Type) 10;
  336. test.expect (a.value == c);
  337. test.expect (a.get() == c);
  338. a += 15;
  339. c += 15;
  340. test.expect (a.get() == c);
  341. a.memoryBarrier();
  342. a -= 5;
  343. c -= 5;
  344. test.expect (a.get() == c);
  345. test.expect (++a == ++c);
  346. ++a;
  347. ++c;
  348. test.expect (--a == --c);
  349. test.expect (a.get() == c);
  350. a.memoryBarrier();
  351. testFloat (test);
  352. }
  353. static void testFloat (UnitTest& test)
  354. {
  355. Atomic<Type> a, b;
  356. a = (Type) 101;
  357. a.memoryBarrier();
  358. /* These are some simple test cases to check the atomics - let me know
  359. if any of these assertions fail on your system!
  360. */
  361. test.expect (a.get() == (Type) 101);
  362. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  363. test.expect (a.get() == (Type) 101);
  364. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  365. test.expect (a.get() == (Type) 200);
  366. test.expect (a.exchange ((Type) 300) == (Type) 200);
  367. test.expect (a.get() == (Type) 300);
  368. b = a;
  369. test.expect (b.get() == a.get());
  370. }
  371. };
  372. };
  373. static AtomicTests atomicUnitTests;
  374. //==============================================================================
  375. class ThreadLocalValueUnitTest : public UnitTest,
  376. private Thread
  377. {
  378. public:
  379. ThreadLocalValueUnitTest()
  380. : UnitTest ("ThreadLocalValue", "Threads"),
  381. Thread ("ThreadLocalValue Thread")
  382. {}
  383. void runTest() override
  384. {
  385. beginTest ("values are thread local");
  386. {
  387. ThreadLocalValue<int> threadLocal;
  388. sharedThreadLocal = &threadLocal;
  389. sharedThreadLocal.get()->get() = 1;
  390. startThread();
  391. signalThreadShouldExit();
  392. waitForThreadToExit (-1);
  393. mainThreadResult = sharedThreadLocal.get()->get();
  394. expectEquals (mainThreadResult.get(), 1);
  395. expectEquals (auxThreadResult.get(), 2);
  396. }
  397. beginTest ("values are per-instance");
  398. {
  399. ThreadLocalValue<int> a, b;
  400. a.get() = 1;
  401. b.get() = 2;
  402. expectEquals (a.get(), 1);
  403. expectEquals (b.get(), 2);
  404. }
  405. }
  406. private:
  407. Atomic<int> mainThreadResult, auxThreadResult;
  408. Atomic<ThreadLocalValue<int>*> sharedThreadLocal;
  409. void run() override
  410. {
  411. sharedThreadLocal.get()->get() = 2;
  412. auxThreadResult = sharedThreadLocal.get()->get();
  413. }
  414. };
  415. ThreadLocalValueUnitTest threadLocalValueUnitTest;
  416. #endif
  417. } // namespace juce