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.

307 lines
12KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2016 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license/
  7. Permission to use, copy, modify, and/or distribute this software for any
  8. purpose with or without fee is hereby granted, provided that the above
  9. copyright notice and this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  11. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  13. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  14. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  15. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  16. OF THIS SOFTWARE.
  17. -----------------------------------------------------------------------------
  18. To release a closed-source product which uses other parts of JUCE not
  19. licensed under the ISC terms, commercial licenses are available: visit
  20. www.juce.com for more information.
  21. ==============================================================================
  22. */
  23. #ifndef JUCE_THREAD_H_INCLUDED
  24. #define JUCE_THREAD_H_INCLUDED
  25. //==============================================================================
  26. /**
  27. Encapsulates a thread.
  28. Subclasses derive from Thread and implement the run() method, in which they
  29. do their business. The thread can then be started with the startThread() method
  30. and controlled with various other methods.
  31. This class also contains some thread-related static methods, such
  32. as sleep(), yield(), getCurrentThreadId() etc.
  33. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  34. MessageManagerLock
  35. */
  36. class JUCE_API Thread
  37. {
  38. public:
  39. //==============================================================================
  40. /**
  41. Creates a thread.
  42. When first created, the thread is not running. Use the startThread()
  43. method to start it.
  44. @param threadName The name of the thread which typically appears in
  45. debug logs and profiles.
  46. @param threadStackSize The size of the stack of the thread. If this value
  47. is zero then the default stack size of the OS will
  48. be used.
  49. */
  50. explicit Thread (const String& threadName, size_t threadStackSize = 0);
  51. /** Destructor.
  52. You must never attempt to delete a Thread object while it's still running -
  53. always call stopThread() and make sure your thread has stopped before deleting
  54. the object. Failing to do so will throw an assertion, and put you firmly into
  55. undefined behaviour territory.
  56. */
  57. virtual ~Thread();
  58. //==============================================================================
  59. /** Must be implemented to perform the thread's actual code.
  60. Remember that the thread must regularly check the threadShouldExit()
  61. method whilst running, and if this returns true it should return from
  62. the run() method as soon as possible to avoid being forcibly killed.
  63. @see threadShouldExit, startThread
  64. */
  65. virtual void run() = 0;
  66. //==============================================================================
  67. // Thread control functions..
  68. /** Starts the thread running.
  69. This will cause the thread's run() method to be called by a new thread.
  70. If this thread is already running, startThread() won't do anything.
  71. @see stopThread
  72. */
  73. void startThread();
  74. /** Starts the thread with a given priority.
  75. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  76. If the thread is already running, its priority will be changed.
  77. @see startThread, setPriority
  78. */
  79. void startThread (int priority);
  80. /** Attempts to stop the thread running.
  81. This method will cause the threadShouldExit() method to return true
  82. and call notify() in case the thread is currently waiting.
  83. Hopefully the thread will then respond to this by exiting cleanly, and
  84. the stopThread method will wait for a given time-period for this to
  85. happen.
  86. If the thread is stuck and fails to respond after the time-out, it gets
  87. forcibly killed, which is a very bad thing to happen, as it could still
  88. be holding locks, etc. which are needed by other parts of your program.
  89. @param timeOutMilliseconds The number of milliseconds to wait for the
  90. thread to finish before killing it by force. A negative
  91. value in here will wait forever.
  92. @returns true if the thread was cleanly stopped before the timeout, or false
  93. if it had to be killed by force.
  94. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  95. */
  96. bool stopThread (int timeOutMilliseconds);
  97. //==============================================================================
  98. /** Returns true if the thread is currently active */
  99. bool isThreadRunning() const;
  100. /** Sets a flag to tell the thread it should stop.
  101. Calling this means that the threadShouldExit() method will then return true.
  102. The thread should be regularly checking this to see whether it should exit.
  103. If your thread makes use of wait(), you might want to call notify() after calling
  104. this method, to interrupt any waits that might be in progress, and allow it
  105. to reach a point where it can exit.
  106. @see threadShouldExit
  107. @see waitForThreadToExit
  108. */
  109. void signalThreadShouldExit();
  110. /** Checks whether the thread has been told to stop running.
  111. Threads need to check this regularly, and if it returns true, they should
  112. return from their run() method at the first possible opportunity.
  113. @see signalThreadShouldExit, currentThreadShouldExit
  114. */
  115. bool threadShouldExit() const { return shouldExit; }
  116. /** Checks whether the current thread has been told to stop running.
  117. On the message thread, this will always return false, otherwise
  118. it will return threadShouldExit() called on the current thread.
  119. @see threadShouldExit
  120. */
  121. static bool currentThreadShouldExit();
  122. /** Waits for the thread to stop.
  123. This will waits until isThreadRunning() is false or until a timeout expires.
  124. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  125. is less than zero, it will wait forever.
  126. @returns true if the thread exits, or false if the timeout expires first.
  127. */
  128. bool waitForThreadToExit (int timeOutMilliseconds) const;
  129. //==============================================================================
  130. /** Changes the thread's priority.
  131. May return false if for some reason the priority can't be changed.
  132. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  133. of 5 is normal.
  134. */
  135. bool setPriority (int priority);
  136. /** Changes the priority of the caller thread.
  137. Similar to setPriority(), but this static method acts on the caller thread.
  138. May return false if for some reason the priority can't be changed.
  139. @see setPriority
  140. */
  141. static bool setCurrentThreadPriority (int priority);
  142. //==============================================================================
  143. /** Sets the affinity mask for the thread.
  144. This will only have an effect next time the thread is started - i.e. if the
  145. thread is already running when called, it'll have no effect.
  146. @see setCurrentThreadAffinityMask
  147. */
  148. void setAffinityMask (uint32 affinityMask);
  149. /** Changes the affinity mask for the caller thread.
  150. This will change the affinity mask for the thread that calls this static method.
  151. @see setAffinityMask
  152. */
  153. static void JUCE_CALLTYPE setCurrentThreadAffinityMask (uint32 affinityMask);
  154. //==============================================================================
  155. // this can be called from any thread that needs to pause..
  156. static void JUCE_CALLTYPE sleep (int milliseconds);
  157. /** Yields the calling thread's current time-slot. */
  158. static void JUCE_CALLTYPE yield();
  159. //==============================================================================
  160. /** Makes the thread wait for a notification.
  161. This puts the thread to sleep until either the timeout period expires, or
  162. another thread calls the notify() method to wake it up.
  163. A negative time-out value means that the method will wait indefinitely.
  164. @returns true if the event has been signalled, false if the timeout expires.
  165. */
  166. bool wait (int timeOutMilliseconds) const;
  167. /** Wakes up the thread.
  168. If the thread has called the wait() method, this will wake it up.
  169. @see wait
  170. */
  171. void notify() const;
  172. //==============================================================================
  173. /** A value type used for thread IDs.
  174. @see getCurrentThreadId(), getThreadId()
  175. */
  176. typedef void* ThreadID;
  177. /** Returns an id that identifies the caller thread.
  178. To find the ID of a particular thread object, use getThreadId().
  179. @returns a unique identifier that identifies the calling thread.
  180. @see getThreadId
  181. */
  182. static ThreadID JUCE_CALLTYPE getCurrentThreadId();
  183. /** Finds the thread object that is currently running.
  184. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  185. object associated with them, so this will return nullptr.
  186. */
  187. static Thread* JUCE_CALLTYPE getCurrentThread();
  188. /** Returns the ID of this thread.
  189. That means the ID of this thread object - not of the thread that's calling the method.
  190. This can change when the thread is started and stopped, and will be invalid if the
  191. thread's not actually running.
  192. @see getCurrentThreadId
  193. */
  194. ThreadID getThreadId() const noexcept { return threadId; }
  195. /** Returns the name of the thread.
  196. This is the name that gets set in the constructor.
  197. */
  198. const String& getThreadName() const { return threadName; }
  199. /** Changes the name of the caller thread.
  200. Different OSes may place different length or content limits on this name.
  201. */
  202. static void JUCE_CALLTYPE setCurrentThreadName (const String& newThreadName);
  203. private:
  204. //==============================================================================
  205. const String threadName;
  206. void* volatile threadHandle;
  207. ThreadID threadId;
  208. CriticalSection startStopLock;
  209. WaitableEvent startSuspensionEvent, defaultEvent;
  210. int threadPriority;
  211. size_t threadStackSize;
  212. uint32 affinityMask;
  213. bool volatile shouldExit;
  214. #ifndef DOXYGEN
  215. friend void JUCE_API juce_threadEntryPoint (void*);
  216. #endif
  217. void launchThread();
  218. void closeThreadHandle();
  219. void killThread();
  220. void threadEntryPoint();
  221. static bool setThreadPriority (void*, int);
  222. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread)
  223. };
  224. #endif // JUCE_THREAD_H_INCLUDED