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.

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