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.

532 lines
15KB

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