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.

491 lines
20KB

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