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.

613 lines
24KB

  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. /**
  21. Encapsulates a thread.
  22. Subclasses derive from Thread and implement the run() method, in which they
  23. do their business. The thread can then be started with the startThread() or
  24. startRealtimeThread() methods and controlled with various other methods.
  25. This class also contains some thread-related static methods, such
  26. as sleep(), yield(), getCurrentThreadId() etc.
  27. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  28. MessageManagerLock
  29. @tags{Core}
  30. */
  31. class JUCE_API Thread
  32. {
  33. public:
  34. //==============================================================================
  35. static constexpr size_t osDefaultStackSize { 0 };
  36. //==============================================================================
  37. /** The different runtime priorities of non-realtime threads.
  38. @see startThread
  39. */
  40. enum class Priority
  41. {
  42. /** The highest possible priority that isn't a dedicated realtime thread. */
  43. highest = 2,
  44. /** Makes use of performance cores and higher clocks. */
  45. high = 1,
  46. /** The OS default. It will balance out across all cores. */
  47. normal = 0,
  48. /** Uses efficiency cores when possible. */
  49. low = -1,
  50. /** Restricted to efficiency cores on platforms that have them. */
  51. background = -2
  52. };
  53. //==============================================================================
  54. /** A selection of options available when creating realtime threads.
  55. @see startRealtimeThread
  56. */
  57. struct RealtimeOptions
  58. {
  59. /** A value with a range of 0-10, where 10 is the highest priority.
  60. Currently only used by Posix platforms.
  61. @see getPriority
  62. */
  63. [[nodiscard]] RealtimeOptions withPriority (int newPriority) const
  64. {
  65. jassert (isPositiveAndNotGreaterThan (newPriority, 10));
  66. return withMember (*this, &RealtimeOptions::priority, juce::jlimit (0, 10, newPriority));
  67. }
  68. /** Specify the expected amount of processing time required each time the thread wakes up.
  69. Only used by macOS/iOS.
  70. @see getProcessingTimeMs, withMaximumProcessingTimeMs, withPeriodMs, withPeriodHz
  71. */
  72. [[nodiscard]] RealtimeOptions withProcessingTimeMs (double newProcessingTimeMs) const
  73. {
  74. jassert (newProcessingTimeMs > 0.0);
  75. return withMember (*this, &RealtimeOptions::processingTimeMs, newProcessingTimeMs);
  76. }
  77. /** Specify the maximum amount of processing time required each time the thread wakes up.
  78. Only used by macOS/iOS.
  79. @see getMaximumProcessingTimeMs, withProcessingTimeMs, withPeriodMs, withPeriodHz
  80. */
  81. [[nodiscard]] RealtimeOptions withMaximumProcessingTimeMs (double newMaximumProcessingTimeMs) const
  82. {
  83. jassert (newMaximumProcessingTimeMs > 0.0);
  84. return withMember (*this, &RealtimeOptions::maximumProcessingTimeMs, newMaximumProcessingTimeMs);
  85. }
  86. /** Specify the maximum amount of processing time required each time the thread wakes up.
  87. This is identical to 'withMaximumProcessingTimeMs' except it calculates the processing time
  88. from a sample rate and block size. This is useful if you want to run this thread in parallel
  89. to an audio device thread.
  90. Only used by macOS/iOS.
  91. @see withMaximumProcessingTimeMs, AudioWorkgroup, ScopedWorkgroupToken
  92. */
  93. [[nodiscard]] RealtimeOptions withApproximateAudioProcessingTime (int samplesPerFrame, double sampleRate) const
  94. {
  95. jassert (samplesPerFrame > 0);
  96. jassert (sampleRate > 0.0);
  97. const auto approxFrameTimeMs = (samplesPerFrame / sampleRate) * 1000.0;
  98. return withMaximumProcessingTimeMs (approxFrameTimeMs);
  99. }
  100. /** Specify the approximate amount of time between each thread wake up.
  101. Alternatively call withPeriodHz().
  102. Only used by macOS/iOS.
  103. @see getPeriodMs, withPeriodHz, withProcessingTimeMs, withMaximumProcessingTimeMs,
  104. */
  105. [[nodiscard]] RealtimeOptions withPeriodMs (double newPeriodMs) const
  106. {
  107. jassert (newPeriodMs > 0.0);
  108. return withMember (*this, &RealtimeOptions::periodMs, newPeriodMs);
  109. }
  110. /** Specify the approximate frequency at which the thread will be woken up.
  111. Alternatively call withPeriodMs().
  112. Only used by macOS/iOS.
  113. @see getPeriodHz, withPeriodMs, withProcessingTimeMs, withMaximumProcessingTimeMs,
  114. */
  115. [[nodiscard]] RealtimeOptions withPeriodHz (double newPeriodHz) const
  116. {
  117. jassert (newPeriodHz > 0.0);
  118. return withPeriodMs (1'000.0 / newPeriodHz);
  119. }
  120. /** Returns a value with a range of 0-10, where 10 is the highest priority.
  121. @see withPriority
  122. */
  123. [[nodiscard]] int getPriority() const
  124. {
  125. return priority;
  126. }
  127. /** Returns the expected amount of processing time required each time the thread
  128. wakes up.
  129. @see withProcessingTimeMs, getMaximumProcessingTimeMs, getPeriodMs
  130. */
  131. [[nodiscard]] std::optional<double> getProcessingTimeMs() const
  132. {
  133. return processingTimeMs;
  134. }
  135. /** Returns the maximum amount of processing time required each time the thread
  136. wakes up.
  137. @see withMaximumProcessingTimeMs, getProcessingTimeMs, getPeriodMs
  138. */
  139. [[nodiscard]] std::optional<double> getMaximumProcessingTimeMs() const
  140. {
  141. return maximumProcessingTimeMs;
  142. }
  143. /** Returns the approximate amount of time between each thread wake up, or
  144. nullopt if there is no inherent periodicity.
  145. @see withPeriodMs, withPeriodHz, getProcessingTimeMs, getMaximumProcessingTimeMs
  146. */
  147. [[nodiscard]] std::optional<double> getPeriodMs() const
  148. {
  149. return periodMs;
  150. }
  151. private:
  152. int priority { 5 };
  153. std::optional<double> processingTimeMs;
  154. std::optional<double> maximumProcessingTimeMs;
  155. std::optional<double> periodMs{};
  156. };
  157. //==============================================================================
  158. /**
  159. Creates a thread.
  160. When first created, the thread is not running. Use the startThread()
  161. method to start it.
  162. @param threadName The name of the thread which typically appears in
  163. debug logs and profiles.
  164. @param threadStackSize The size of the stack of the thread. If this value
  165. is zero then the default stack size of the OS will
  166. be used.
  167. */
  168. explicit Thread (const String& threadName, size_t threadStackSize = osDefaultStackSize);
  169. /** Destructor.
  170. You must never attempt to delete a Thread object while it's still running -
  171. always call stopThread() and make sure your thread has stopped before deleting
  172. the object. Failing to do so will throw an assertion, and put you firmly into
  173. undefined behaviour territory.
  174. */
  175. virtual ~Thread();
  176. //==============================================================================
  177. /** Must be implemented to perform the thread's actual code.
  178. Remember that the thread must regularly check the threadShouldExit()
  179. method whilst running, and if this returns true it should return from
  180. the run() method as soon as possible to avoid being forcibly killed.
  181. @see threadShouldExit, startThread
  182. */
  183. virtual void run() = 0;
  184. //==============================================================================
  185. /** Attempts to start a new thread with default ('Priority::normal') priority.
  186. This will cause the thread's run() method to be called by a new thread.
  187. If this thread is already running, startThread() won't do anything.
  188. If a thread cannot be created with the requested priority, this will return false
  189. and Thread::run() will not be called. An exception to this is the Android platform,
  190. which always starts a thread and attempts to upgrade the thread after creation.
  191. @returns true if the thread started successfully. false if it was unsuccesful.
  192. @see stopThread
  193. */
  194. bool startThread();
  195. /** Attempts to start a new thread with a given priority.
  196. This will cause the thread's run() method to be called by a new thread.
  197. If this thread is already running, startThread() won't do anything.
  198. If a thread cannot be created with the requested priority, this will return false
  199. and Thread::run() will not be called. An exception to this is the Android platform,
  200. which always starts a thread and attempts to upgrade the thread after creation.
  201. @param newPriority Priority the thread should be assigned. This parameter is ignored
  202. on Linux.
  203. @returns true if the thread started successfully, false if it was unsuccesful.
  204. @see startThread, setPriority, startRealtimeThread
  205. */
  206. bool startThread (Priority newPriority);
  207. /** Starts the thread with realtime performance characteristics on platforms
  208. that support it.
  209. You cannot change the options of a running realtime thread, nor switch
  210. a non-realtime thread to a realtime thread. To make these changes you must
  211. first stop the thread and then restart with different options.
  212. @param options Realtime options the thread should be created with.
  213. @see startThread, RealtimeOptions
  214. */
  215. bool startRealtimeThread (const RealtimeOptions& options);
  216. /** Attempts to stop the thread running.
  217. This method will cause the threadShouldExit() method to return true
  218. and call notify() in case the thread is currently waiting.
  219. Hopefully the thread will then respond to this by exiting cleanly, and
  220. the stopThread method will wait for a given time-period for this to
  221. happen.
  222. If the thread is stuck and fails to respond after the timeout, it gets
  223. forcibly killed, which is a very bad thing to happen, as it could still
  224. be holding locks, etc. which are needed by other parts of your program.
  225. @param timeOutMilliseconds The number of milliseconds to wait for the
  226. thread to finish before killing it by force. A negative
  227. value in here will wait forever.
  228. @returns true if the thread was cleanly stopped before the timeout, or false
  229. if it had to be killed by force.
  230. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  231. */
  232. bool stopThread (int timeOutMilliseconds);
  233. //==============================================================================
  234. /** Invokes a lambda or function on its own thread with the default priority.
  235. This will spin up a Thread object which calls the function and then exits.
  236. Bear in mind that starting and stopping a thread can be a fairly heavyweight
  237. operation, so you might prefer to use a ThreadPool if you're kicking off a lot
  238. of short background tasks.
  239. Also note that using an anonymous thread makes it very difficult to interrupt
  240. the function when you need to stop it, e.g. when your app quits. So it's up to
  241. you to deal with situations where the function may fail to stop in time.
  242. @param functionToRun The lambda to be called from the new Thread.
  243. @returns true if the thread started successfully, or false if it failed.
  244. @see launch.
  245. */
  246. static bool launch (std::function<void()> functionToRun);
  247. //==============================================================================
  248. /** Invokes a lambda or function on its own thread with a custom priority.
  249. This will spin up a Thread object which calls the function and then exits.
  250. Bear in mind that starting and stopping a thread can be a fairly heavyweight
  251. operation, so you might prefer to use a ThreadPool if you're kicking off a lot
  252. of short background tasks.
  253. Also note that using an anonymous thread makes it very difficult to interrupt
  254. the function when you need to stop it, e.g. when your app quits. So it's up to
  255. you to deal with situations where the function may fail to stop in time.
  256. @param priority The priority the thread is started with.
  257. @param functionToRun The lambda to be called from the new Thread.
  258. @returns true if the thread started successfully, or false if it failed.
  259. */
  260. static bool launch (Priority priority, std::function<void()> functionToRun);
  261. //==============================================================================
  262. /** Returns true if the thread is currently active */
  263. bool isThreadRunning() const;
  264. /** Sets a flag to tell the thread it should stop.
  265. Calling this means that the threadShouldExit() method will then return true.
  266. The thread should be regularly checking this to see whether it should exit.
  267. If your thread makes use of wait(), you might want to call notify() after calling
  268. this method, to interrupt any waits that might be in progress, and allow it
  269. to reach a point where it can exit.
  270. @see threadShouldExit, waitForThreadToExit
  271. */
  272. void signalThreadShouldExit();
  273. /** Checks whether the thread has been told to stop running.
  274. Threads need to check this regularly, and if it returns true, they should
  275. return from their run() method at the first possible opportunity.
  276. @see signalThreadShouldExit, currentThreadShouldExit
  277. */
  278. bool threadShouldExit() const;
  279. /** Checks whether the current thread has been told to stop running.
  280. On the message thread, this will always return false, otherwise
  281. it will return threadShouldExit() called on the current thread.
  282. @see threadShouldExit
  283. */
  284. static bool currentThreadShouldExit();
  285. /** Waits for the thread to stop.
  286. This will wait until isThreadRunning() is false or until a timeout expires.
  287. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  288. is less than zero, it will wait forever.
  289. @returns true if the thread exits, or false if the timeout expires first.
  290. */
  291. bool waitForThreadToExit (int timeOutMilliseconds) const;
  292. //==============================================================================
  293. /** Used to receive callbacks for thread exit calls */
  294. class JUCE_API Listener
  295. {
  296. public:
  297. virtual ~Listener() = default;
  298. /** Called if Thread::signalThreadShouldExit was called.
  299. @see Thread::threadShouldExit, Thread::addListener, Thread::removeListener
  300. */
  301. virtual void exitSignalSent() = 0;
  302. };
  303. /** Add a listener to this thread which will receive a callback when
  304. signalThreadShouldExit was called on this thread.
  305. @see signalThreadShouldExit, removeListener
  306. */
  307. void addListener (Listener*);
  308. /** Removes a listener added with addListener. */
  309. void removeListener (Listener*);
  310. /** Returns true if this Thread represents a realtime thread. */
  311. bool isRealtime() const;
  312. //==============================================================================
  313. /** Sets the affinity mask for the thread.
  314. This will only have an effect next time the thread is started - i.e. if the
  315. thread is already running when called, it'll have no effect.
  316. @see setCurrentThreadAffinityMask
  317. */
  318. void setAffinityMask (uint32 affinityMask);
  319. /** Changes the affinity mask for the caller thread.
  320. This will change the affinity mask for the thread that calls this static method.
  321. @see setAffinityMask
  322. */
  323. static void JUCE_CALLTYPE setCurrentThreadAffinityMask (uint32 affinityMask);
  324. //==============================================================================
  325. /** Suspends the execution of the current thread until the specified timeout period
  326. has elapsed (note that this may not be exact).
  327. The timeout period must not be negative and whilst sleeping the thread cannot
  328. be woken up so it should only be used for short periods of time and when other
  329. methods such as using a WaitableEvent or CriticalSection are not possible.
  330. */
  331. static void JUCE_CALLTYPE sleep (int milliseconds);
  332. /** Yields the current thread's CPU time-slot and allows a new thread to run.
  333. If there are no other threads of equal or higher priority currently running then
  334. this will return immediately and the current thread will continue to run.
  335. */
  336. static void JUCE_CALLTYPE yield();
  337. //==============================================================================
  338. /** Suspends the execution of this thread until either the specified timeout period
  339. has elapsed, or another thread calls the notify() method to wake it up.
  340. A negative timeout value means that the method will wait indefinitely.
  341. @returns true if the event has been signalled, false if the timeout expires.
  342. */
  343. bool wait (double timeOutMilliseconds) const;
  344. /** Wakes up the thread.
  345. If the thread has called the wait() method, this will wake it up.
  346. @see wait
  347. */
  348. void notify() const;
  349. //==============================================================================
  350. /** A value type used for thread IDs.
  351. @see getCurrentThreadId(), getThreadId()
  352. */
  353. using ThreadID = void*;
  354. /** Returns an id that identifies the caller thread.
  355. To find the ID of a particular thread object, use getThreadId().
  356. @returns a unique identifier that identifies the calling thread.
  357. @see getThreadId
  358. */
  359. static ThreadID JUCE_CALLTYPE getCurrentThreadId();
  360. /** Finds the thread object that is currently running.
  361. Note that the main UI thread (or other non-JUCE threads) don't have a Thread
  362. object associated with them, so this will return nullptr.
  363. */
  364. static Thread* JUCE_CALLTYPE getCurrentThread();
  365. /** Returns the ID of this thread.
  366. That means the ID of this thread object - not of the thread that's calling the method.
  367. This can change when the thread is started and stopped, and will be invalid if the
  368. thread's not actually running.
  369. @see getCurrentThreadId
  370. */
  371. ThreadID getThreadId() const noexcept;
  372. /** Returns the name of the thread. This is the name that gets set in the constructor. */
  373. const String& getThreadName() const noexcept { return threadName; }
  374. /** Changes the name of the caller thread.
  375. Different OSes may place different length or content limits on this name.
  376. */
  377. static void JUCE_CALLTYPE setCurrentThreadName (const String& newThreadName);
  378. #if JUCE_ANDROID || DOXYGEN
  379. //==============================================================================
  380. /** Initialises the JUCE subsystem for projects not created by the Projucer
  381. On Android, JUCE needs to be initialised once before it is used. The Projucer
  382. will automatically generate the necessary java code to do this. However, if
  383. you are using JUCE without the Projucer or are creating a library made with
  384. JUCE intended for use in non-JUCE apks, then you must call this method
  385. manually once on apk startup.
  386. You can call this method from C++ or directly from java by calling the
  387. following java method:
  388. @code
  389. com.rmsl.juce.Java.initialiseJUCE (myContext);
  390. @endcode
  391. Note that the above java method is only available in Android Studio projects
  392. created by the Projucer. If you need to call this from another type of project
  393. then you need to add the following java file to
  394. your project:
  395. @code
  396. package com.rmsl.juce;
  397. public class Java
  398. {
  399. static { System.loadLibrary ("juce_jni"); }
  400. public native static void initialiseJUCE (Context context);
  401. }
  402. @endcode
  403. @param jniEnv this is a pointer to JNI's JNIEnv variable. Any callback
  404. from Java into C++ will have this passed in as it's first
  405. parameter.
  406. @param jContext this is a jobject referring to your app/service/receiver/
  407. provider's Context. JUCE needs this for many of it's internal
  408. functions.
  409. */
  410. static void initialiseJUCE (void* jniEnv, void* jContext);
  411. #endif
  412. protected:
  413. //==============================================================================
  414. /** Returns the current priority of this thread.
  415. This can only be called from the target thread. Doing so from another thread
  416. will cause an assert.
  417. @see setPriority
  418. */
  419. Priority getPriority() const;
  420. /** Attempts to set the priority for this thread. Returns true if the new priority
  421. was set successfully, false if not.
  422. This can only be called from the target thread. Doing so from another thread
  423. will cause an assert.
  424. @param newPriority The new priority to be applied to the thread. Note: This
  425. has no effect on Linux platforms, subsequent calls to
  426. 'getPriority' will return this value.
  427. @see Priority
  428. */
  429. bool setPriority (Priority newPriority);
  430. private:
  431. //==============================================================================
  432. const String threadName;
  433. std::atomic<void*> threadHandle { nullptr };
  434. std::atomic<ThreadID> threadId { nullptr };
  435. std::optional<RealtimeOptions> realtimeOptions = {};
  436. CriticalSection startStopLock;
  437. WaitableEvent startSuspensionEvent, defaultEvent;
  438. size_t threadStackSize;
  439. uint32 affinityMask = 0;
  440. bool deleteOnThreadEnd = false;
  441. std::atomic<bool> shouldExit { false };
  442. ListenerList<Listener, Array<Listener*, CriticalSection>> listeners;
  443. #if JUCE_ANDROID || JUCE_LINUX || JUCE_BSD
  444. std::atomic<Priority> priority;
  445. #endif
  446. #ifndef DOXYGEN
  447. friend void JUCE_API juce_threadEntryPoint (void*);
  448. #endif
  449. bool startThreadInternal (Priority);
  450. bool createNativeThread (Priority);
  451. void closeThreadHandle();
  452. void killThread();
  453. void threadEntryPoint();
  454. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread)
  455. };
  456. } // namespace juce