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.

416 lines
16KB

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