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.

327 lines
12KB

  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. #pragma once
  18. //==============================================================================
  19. /**
  20. Encapsulates a thread.
  21. Subclasses derive from Thread and implement the run() method, in which they
  22. do their business. The thread can then be started with the startThread() method
  23. and controlled with various other methods.
  24. This class also contains some thread-related static methods, such
  25. as sleep(), yield(), getCurrentThreadId() etc.
  26. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  27. MessageManagerLock
  28. */
  29. class JUCE_API Thread
  30. {
  31. public:
  32. //==============================================================================
  33. /**
  34. Creates a thread.
  35. When first created, the thread is not running. Use the startThread()
  36. method to start it.
  37. @param threadName The name of the thread which typically appears in
  38. debug logs and profiles.
  39. @param threadStackSize The size of the stack of the thread. If this value
  40. is zero then the default stack size of the OS will
  41. be used.
  42. */
  43. explicit Thread (const String& threadName, size_t threadStackSize = 0);
  44. /** Destructor.
  45. You must never attempt to delete a Thread object while it's still running -
  46. always call stopThread() and make sure your thread has stopped before deleting
  47. the object. Failing to do so will throw an assertion, and put you firmly into
  48. undefined behaviour territory.
  49. */
  50. virtual ~Thread();
  51. //==============================================================================
  52. /** Must be implemented to perform the thread's actual code.
  53. Remember that the thread must regularly check the threadShouldExit()
  54. method whilst running, and if this returns true it should return from
  55. the run() method as soon as possible to avoid being forcibly killed.
  56. @see threadShouldExit, startThread
  57. */
  58. virtual void run() = 0;
  59. //==============================================================================
  60. // Thread control functions..
  61. /** Starts the thread running.
  62. This will cause the thread's run() method to be called by a new thread.
  63. If this thread is already running, startThread() won't do anything.
  64. @see stopThread
  65. */
  66. void startThread();
  67. /** Starts the thread with a given priority.
  68. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  69. If the thread is already running, its priority will be changed.
  70. @see startThread, setPriority, realtimeAudioPriority
  71. */
  72. void startThread (int priority);
  73. /** Attempts to stop the thread running.
  74. This method will cause the threadShouldExit() method to return true
  75. and call notify() in case the thread is currently waiting.
  76. Hopefully the thread will then respond to this by exiting cleanly, and
  77. the stopThread method will wait for a given time-period for this to
  78. happen.
  79. If the thread is stuck and fails to respond after the time-out, it gets
  80. forcibly killed, which is a very bad thing to happen, as it could still
  81. be holding locks, etc. which are needed by other parts of your program.
  82. @param timeOutMilliseconds The number of milliseconds to wait for the
  83. thread to finish before killing it by force. A negative
  84. value in here will wait forever.
  85. @returns true if the thread was cleanly stopped before the timeout, or false
  86. if it had to be killed by force.
  87. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  88. */
  89. bool stopThread (int timeOutMilliseconds);
  90. //==============================================================================
  91. /** Returns true if the thread is currently active */
  92. bool isThreadRunning() const;
  93. /** Sets a flag to tell the thread it should stop.
  94. Calling this means that the threadShouldExit() method will then return true.
  95. The thread should be regularly checking this to see whether it should exit.
  96. If your thread makes use of wait(), you might want to call notify() after calling
  97. this method, to interrupt any waits that might be in progress, and allow it
  98. to reach a point where it can exit.
  99. @see threadShouldExit
  100. @see waitForThreadToExit
  101. */
  102. void signalThreadShouldExit();
  103. /** Checks whether the thread has been told to stop running.
  104. Threads need to check this regularly, and if it returns true, they should
  105. return from their run() method at the first possible opportunity.
  106. @see signalThreadShouldExit, currentThreadShouldExit
  107. */
  108. bool threadShouldExit() const { return shouldExit; }
  109. /** Checks whether the current thread has been told to stop running.
  110. On the message thread, this will always return false, otherwise
  111. it will return threadShouldExit() called on the current thread.
  112. @see threadShouldExit
  113. */
  114. static bool currentThreadShouldExit();
  115. /** Waits for the thread to stop.
  116. This will waits until isThreadRunning() is false or until a timeout expires.
  117. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  118. is less than zero, it will wait forever.
  119. @returns true if the thread exits, or false if the timeout expires first.
  120. */
  121. bool waitForThreadToExit (int timeOutMilliseconds) const;
  122. //==============================================================================
  123. /** Special realtime audio thread priority
  124. This priority will create a high-priority thread which is best suited
  125. for realtime audio processing.
  126. Currently, this priority is identical to priority 9, except when building
  127. for Android with OpenSL support.
  128. In this case, JUCE will ask OpenSL to consturct a super high priority thread
  129. specifically for realtime audio processing.
  130. Note that this priority can only be set **before** the thread has
  131. started. Switching to this priority, or from this priority to a different
  132. priority, is not supported under Android and will assert.
  133. For best performance this thread should yield at regular intervals
  134. and not call any blocking APIS.
  135. @see startThread, setPriority, sleep, WaitableEvent
  136. */
  137. enum
  138. {
  139. realtimeAudioPriority = -1
  140. };
  141. /** Changes the thread's priority.
  142. May return false if for some reason the priority can't be changed.
  143. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  144. of 5 is normal.
  145. @see realtimeAudioPriority
  146. */
  147. bool setPriority (int priority);
  148. /** Changes the priority of the caller thread.
  149. Similar to setPriority(), but this static method acts on the caller thread.
  150. May return false if for some reason the priority can't be changed.
  151. @see setPriority
  152. */
  153. static bool setCurrentThreadPriority (int priority);
  154. //==============================================================================
  155. /** Sets the affinity mask for the thread.
  156. This will only have an effect next time the thread is started - i.e. if the
  157. thread is already running when called, it'll have no effect.
  158. @see setCurrentThreadAffinityMask
  159. */
  160. void setAffinityMask (uint32 affinityMask);
  161. /** Changes the affinity mask for the caller thread.
  162. This will change the affinity mask for the thread that calls this static method.
  163. @see setAffinityMask
  164. */
  165. static void JUCE_CALLTYPE setCurrentThreadAffinityMask (uint32 affinityMask);
  166. //==============================================================================
  167. // this can be called from any thread that needs to pause..
  168. static void JUCE_CALLTYPE sleep (int milliseconds);
  169. /** Yields the calling thread's current time-slot. */
  170. static void JUCE_CALLTYPE yield();
  171. //==============================================================================
  172. /** Makes the thread wait for a notification.
  173. This puts the thread to sleep until either the timeout period expires, or
  174. another thread calls the notify() method to wake it up.
  175. A negative time-out value means that the method will wait indefinitely.
  176. @returns true if the event has been signalled, false if the timeout expires.
  177. */
  178. bool wait (int timeOutMilliseconds) const;
  179. /** Wakes up the thread.
  180. If the thread has called the wait() method, this will wake it up.
  181. @see wait
  182. */
  183. void notify() const;
  184. //==============================================================================
  185. /** A value type used for thread IDs.
  186. @see getCurrentThreadId(), getThreadId()
  187. */
  188. typedef void* ThreadID;
  189. /** Returns an id that identifies the caller thread.
  190. To find the ID of a particular thread object, use getThreadId().
  191. @returns a unique identifier that identifies the calling thread.
  192. @see getThreadId
  193. */
  194. static ThreadID JUCE_CALLTYPE getCurrentThreadId();
  195. /** Finds the thread object that is currently running.
  196. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  197. object associated with them, so this will return nullptr.
  198. */
  199. static Thread* JUCE_CALLTYPE getCurrentThread();
  200. /** Returns the ID of this thread.
  201. That means the ID of this thread object - not of the thread that's calling the method.
  202. This can change when the thread is started and stopped, and will be invalid if the
  203. thread's not actually running.
  204. @see getCurrentThreadId
  205. */
  206. ThreadID getThreadId() const noexcept { return threadId; }
  207. /** Returns the name of the thread.
  208. This is the name that gets set in the constructor.
  209. */
  210. const String& getThreadName() const { return threadName; }
  211. /** Changes the name of the caller thread.
  212. Different OSes may place different length or content limits on this name.
  213. */
  214. static void JUCE_CALLTYPE setCurrentThreadName (const String& newThreadName);
  215. private:
  216. //==============================================================================
  217. const String threadName;
  218. void* volatile threadHandle = nullptr;
  219. ThreadID threadId = {};
  220. CriticalSection startStopLock;
  221. WaitableEvent startSuspensionEvent, defaultEvent;
  222. int threadPriority = 5;
  223. size_t threadStackSize;
  224. uint32 affinityMask = 0;
  225. bool volatile shouldExit = false;
  226. #if JUCE_ANDROID
  227. bool isAndroidRealtimeThread = false;
  228. #endif
  229. #ifndef DOXYGEN
  230. friend void JUCE_API juce_threadEntryPoint (void*);
  231. #endif
  232. void launchThread();
  233. void closeThreadHandle();
  234. void killThread();
  235. void threadEntryPoint();
  236. static bool setThreadPriority (void*, int);
  237. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread)
  238. };