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.

333 lines
13KB

  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. /** Starts the thread running.
  61. This will cause the thread's run() method to be called by a new thread.
  62. If this thread is already running, startThread() won't do anything.
  63. @see stopThread
  64. */
  65. void startThread();
  66. /** Starts the thread with a given priority.
  67. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  68. If the thread is already running, its priority will be changed.
  69. @see startThread, setPriority, realtimeAudioPriority
  70. */
  71. void startThread (int priority);
  72. /** Attempts to stop the thread running.
  73. This method will cause the threadShouldExit() method to return true
  74. and call notify() in case the thread is currently waiting.
  75. Hopefully the thread will then respond to this by exiting cleanly, and
  76. the stopThread method will wait for a given time-period for this to
  77. happen.
  78. If the thread is stuck and fails to respond after the time-out, it gets
  79. forcibly killed, which is a very bad thing to happen, as it could still
  80. be holding locks, etc. which are needed by other parts of your program.
  81. @param timeOutMilliseconds The number of milliseconds to wait for the
  82. thread to finish before killing it by force. A negative
  83. value in here will wait forever.
  84. @returns true if the thread was cleanly stopped before the timeout, or false
  85. if it had to be killed by force.
  86. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  87. */
  88. bool stopThread (int timeOutMilliseconds);
  89. //==============================================================================
  90. /** Invokes a lambda or function on its own thread.
  91. This will spin up a Thread object which calls the function and then exits.
  92. Bear in mind that starting and stopping a thread can be a fairly heavyweight
  93. operation, so you might prefer to use a ThreadPool if you're kicking off a lot
  94. of short background tasks.
  95. Also note that using an anonymous thread makes it very difficult to interrupt
  96. the function when you need to stop it, e.g. when your app quits. So it's up to
  97. you to deal with situations where the function may fail to stop in time.
  98. */
  99. static void launch (std::function<void()> functionToRun);
  100. //==============================================================================
  101. /** Returns true if the thread is currently active */
  102. bool isThreadRunning() const;
  103. /** Sets a flag to tell the thread it should stop.
  104. Calling this means that the threadShouldExit() method will then return true.
  105. The thread should be regularly checking this to see whether it should exit.
  106. If your thread makes use of wait(), you might want to call notify() after calling
  107. this method, to interrupt any waits that might be in progress, and allow it
  108. to reach a point where it can exit.
  109. @see threadShouldExit
  110. @see waitForThreadToExit
  111. */
  112. void signalThreadShouldExit();
  113. /** Checks whether the thread has been told to stop running.
  114. Threads need to check this regularly, and if it returns true, they should
  115. return from their run() method at the first possible opportunity.
  116. @see signalThreadShouldExit, currentThreadShouldExit
  117. */
  118. bool threadShouldExit() const { return shouldExit; }
  119. /** Checks whether the current thread has been told to stop running.
  120. On the message thread, this will always return false, otherwise
  121. it will return threadShouldExit() called on the current thread.
  122. @see threadShouldExit
  123. */
  124. static bool currentThreadShouldExit();
  125. /** Waits for the thread to stop.
  126. This will wait until isThreadRunning() is false or until a timeout expires.
  127. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  128. is less than zero, it will wait forever.
  129. @returns true if the thread exits, or false if the timeout expires first.
  130. */
  131. bool waitForThreadToExit (int timeOutMilliseconds) const;
  132. //==============================================================================
  133. /** Special realtime audio thread priority
  134. This priority will create a high-priority thread which is best suited
  135. for realtime audio processing.
  136. Currently, this priority is identical to priority 9, except when building
  137. for Android with OpenSL support.
  138. In this case, JUCE will ask OpenSL to consturct a super high priority thread
  139. specifically for realtime audio processing.
  140. Note that this priority can only be set **before** the thread has
  141. started. Switching to this priority, or from this priority to a different
  142. priority, is not supported under Android and will assert.
  143. For best performance this thread should yield at regular intervals
  144. and not call any blocking APIS.
  145. @see startThread, setPriority, sleep, WaitableEvent
  146. */
  147. enum
  148. {
  149. realtimeAudioPriority = -1
  150. };
  151. /** Changes the thread's priority.
  152. May return false if for some reason the priority can't be changed.
  153. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  154. of 5 is normal.
  155. @see realtimeAudioPriority
  156. */
  157. bool setPriority (int priority);
  158. /** Changes the priority of the caller thread.
  159. Similar to setPriority(), but this static method acts on the caller thread.
  160. May return false if for some reason the priority can't be changed.
  161. @see setPriority
  162. */
  163. static bool setCurrentThreadPriority (int priority);
  164. //==============================================================================
  165. /** Sets the affinity mask for the thread.
  166. This will only have an effect next time the thread is started - i.e. if the
  167. thread is already running when called, it'll have no effect.
  168. @see setCurrentThreadAffinityMask
  169. */
  170. void setAffinityMask (uint32 affinityMask);
  171. /** Changes the affinity mask for the caller thread.
  172. This will change the affinity mask for the thread that calls this static method.
  173. @see setAffinityMask
  174. */
  175. static void JUCE_CALLTYPE setCurrentThreadAffinityMask (uint32 affinityMask);
  176. //==============================================================================
  177. // this can be called from any thread that needs to pause..
  178. static void JUCE_CALLTYPE sleep (int milliseconds);
  179. /** Yields the calling thread's current time-slot. */
  180. static void JUCE_CALLTYPE yield();
  181. //==============================================================================
  182. /** Makes the thread wait for a notification.
  183. This puts the thread to sleep until either the timeout period expires, or
  184. another thread calls the notify() method to wake it up.
  185. A negative time-out value means that the method will wait indefinitely.
  186. @returns true if the event has been signalled, false if the timeout expires.
  187. */
  188. bool wait (int timeOutMilliseconds) const;
  189. /** Wakes up the thread.
  190. If the thread has called the wait() method, this will wake it up.
  191. @see wait
  192. */
  193. void notify() const;
  194. //==============================================================================
  195. /** A value type used for thread IDs.
  196. @see getCurrentThreadId(), getThreadId()
  197. */
  198. typedef void* ThreadID;
  199. /** Returns an id that identifies the caller thread.
  200. To find the ID of a particular thread object, use getThreadId().
  201. @returns a unique identifier that identifies the calling thread.
  202. @see getThreadId
  203. */
  204. static ThreadID JUCE_CALLTYPE getCurrentThreadId();
  205. /** Finds the thread object that is currently running.
  206. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  207. object associated with them, so this will return nullptr.
  208. */
  209. static Thread* JUCE_CALLTYPE getCurrentThread();
  210. /** Returns the ID of this thread.
  211. That means the ID of this thread object - not of the thread that's calling the method.
  212. This can change when the thread is started and stopped, and will be invalid if the
  213. thread's not actually running.
  214. @see getCurrentThreadId
  215. */
  216. ThreadID getThreadId() const noexcept { return threadId; }
  217. /** Returns the name of the thread.
  218. This is the name that gets set in the constructor.
  219. */
  220. const String& getThreadName() const noexcept { return threadName; }
  221. /** Changes the name of the caller thread.
  222. Different OSes may place different length or content limits on this name.
  223. */
  224. static void JUCE_CALLTYPE setCurrentThreadName (const String& newThreadName);
  225. private:
  226. //==============================================================================
  227. const String threadName;
  228. void* volatile threadHandle = nullptr;
  229. ThreadID threadId = {};
  230. CriticalSection startStopLock;
  231. WaitableEvent startSuspensionEvent, defaultEvent;
  232. int threadPriority = 5;
  233. size_t threadStackSize;
  234. uint32 affinityMask = 0;
  235. bool deleteOnThreadEnd = false;
  236. bool volatile shouldExit = false;
  237. #if JUCE_ANDROID
  238. bool isAndroidRealtimeThread = false;
  239. #endif
  240. #ifndef DOXYGEN
  241. friend void JUCE_API juce_threadEntryPoint (void*);
  242. #endif
  243. void launchThread();
  244. void closeThreadHandle();
  245. void killThread();
  246. void threadEntryPoint();
  247. static bool setThreadPriority (void*, int);
  248. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread)
  249. };