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.

360 lines
14KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  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 time-out, 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
  112. @see waitForThreadToExit
  113. */
  114. void signalThreadShouldExit();
  115. /** Checks whether the thread has been told to stop running.
  116. Threads need to check this regularly, and if it returns true, they should
  117. return from their run() method at the first possible opportunity.
  118. @see signalThreadShouldExit, currentThreadShouldExit
  119. */
  120. bool threadShouldExit() const;
  121. /** Checks whether the current thread has been told to stop running.
  122. On the message thread, this will always return false, otherwise
  123. it will return threadShouldExit() called on the current thread.
  124. @see threadShouldExit
  125. */
  126. static bool currentThreadShouldExit();
  127. /** Waits for the thread to stop.
  128. This will wait until isThreadRunning() is false or until a timeout expires.
  129. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  130. is less than zero, it will wait forever.
  131. @returns true if the thread exits, or false if the timeout expires first.
  132. */
  133. bool waitForThreadToExit (int timeOutMilliseconds) const;
  134. //==============================================================================
  135. /** Used to receive callbacks for thread exit calls */
  136. class JUCE_API Listener
  137. {
  138. public:
  139. virtual ~Listener() {}
  140. /** Called if Thread::signalThreadShouldExit was called.
  141. @see Thread::threadShouldExit, Thread::addListener, Thread::removeListener
  142. */
  143. virtual void exitSignalSent() = 0;
  144. };
  145. /** Add a listener to this thread which will receive a callback when
  146. signalThreadShouldExit was called on this thread.
  147. @see signalThreadShouldExit, removeListener
  148. */
  149. void addListener (Listener*);
  150. /** Removes a listener added with addListener. */
  151. void removeListener (Listener*);
  152. //==============================================================================
  153. /** Special realtime audio thread priority
  154. This priority will create a high-priority thread which is best suited
  155. for realtime audio processing.
  156. Currently, this priority is identical to priority 9, except when building
  157. for Android with OpenSL/Oboe support.
  158. In this case, JUCE will ask OpenSL/Oboe to construct a super high priority thread
  159. specifically for realtime audio processing.
  160. Note that this priority can only be set **before** the thread has
  161. started. Switching to this priority, or from this priority to a different
  162. priority, is not supported under Android and will assert.
  163. For best performance this thread should yield at regular intervals
  164. and not call any blocking APIs.
  165. @see startThread, setPriority, sleep, WaitableEvent
  166. */
  167. enum
  168. {
  169. realtimeAudioPriority = -1
  170. };
  171. /** Changes the thread's priority.
  172. May return false if for some reason the priority can't be changed.
  173. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  174. of 5 is normal.
  175. @see realtimeAudioPriority
  176. */
  177. bool setPriority (int priority);
  178. /** Changes the priority of the caller thread.
  179. Similar to setPriority(), but this static method acts on the caller thread.
  180. May return false if for some reason the priority can't be changed.
  181. @see setPriority
  182. */
  183. static bool setCurrentThreadPriority (int priority);
  184. //==============================================================================
  185. /** Sets the affinity mask for the thread.
  186. This will only have an effect next time the thread is started - i.e. if the
  187. thread is already running when called, it'll have no effect.
  188. @see setCurrentThreadAffinityMask
  189. */
  190. void setAffinityMask (uint32 affinityMask);
  191. /** Changes the affinity mask for the caller thread.
  192. This will change the affinity mask for the thread that calls this static method.
  193. @see setAffinityMask
  194. */
  195. static void JUCE_CALLTYPE setCurrentThreadAffinityMask (uint32 affinityMask);
  196. //==============================================================================
  197. // this can be called from any thread that needs to pause..
  198. static void JUCE_CALLTYPE sleep (int milliseconds);
  199. /** Yields the calling thread's current time-slot. */
  200. static void JUCE_CALLTYPE yield();
  201. //==============================================================================
  202. /** Makes the thread wait for a notification.
  203. This puts the thread to sleep until either the timeout period expires, or
  204. another thread calls the notify() method to wake it up.
  205. A negative time-out value means that the method will wait indefinitely.
  206. @returns true if the event has been signalled, false if the timeout expires.
  207. */
  208. bool wait (int timeOutMilliseconds) const;
  209. /** Wakes up the thread.
  210. If the thread has called the wait() method, this will wake it up.
  211. @see wait
  212. */
  213. void notify() const;
  214. //==============================================================================
  215. /** A value type used for thread IDs.
  216. @see getCurrentThreadId(), getThreadId()
  217. */
  218. using ThreadID = void*;
  219. /** Returns an id that identifies the caller thread.
  220. To find the ID of a particular thread object, use getThreadId().
  221. @returns a unique identifier that identifies the calling thread.
  222. @see getThreadId
  223. */
  224. static ThreadID JUCE_CALLTYPE getCurrentThreadId();
  225. /** Finds the thread object that is currently running.
  226. Note that the main UI thread (or other non-JUCE threads) don't have a Thread
  227. object associated with them, so this will return nullptr.
  228. */
  229. static Thread* JUCE_CALLTYPE getCurrentThread();
  230. /** Returns the ID of this thread.
  231. That means the ID of this thread object - not of the thread that's calling the method.
  232. This can change when the thread is started and stopped, and will be invalid if the
  233. thread's not actually running.
  234. @see getCurrentThreadId
  235. */
  236. ThreadID getThreadId() const noexcept;
  237. /** Returns the name of the thread.
  238. This is the name that gets set in the constructor.
  239. */
  240. const String& getThreadName() const noexcept { return threadName; }
  241. /** Changes the name of the caller thread.
  242. Different OSes may place different length or content limits on this name.
  243. */
  244. static void JUCE_CALLTYPE setCurrentThreadName (const String& newThreadName);
  245. private:
  246. //==============================================================================
  247. const String threadName;
  248. Atomic<void*> threadHandle { nullptr };
  249. Atomic<ThreadID> threadId = {};
  250. CriticalSection startStopLock;
  251. WaitableEvent startSuspensionEvent, defaultEvent;
  252. int threadPriority = 5;
  253. size_t threadStackSize;
  254. uint32 affinityMask = 0;
  255. bool deleteOnThreadEnd = false;
  256. Atomic<int32> shouldExit { 0 };
  257. ListenerList<Listener, Array<Listener*, CriticalSection>> listeners;
  258. #if JUCE_ANDROID
  259. bool isAndroidRealtimeThread = false;
  260. #endif
  261. #ifndef DOXYGEN
  262. friend void JUCE_API juce_threadEntryPoint (void*);
  263. #endif
  264. void launchThread();
  265. void closeThreadHandle();
  266. void killThread();
  267. void threadEntryPoint();
  268. static bool setThreadPriority (void*, int);
  269. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread)
  270. };
  271. } // namespace juce