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.

304 lines
11KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. #ifndef __JUCE_THREAD_JUCEHEADER__
  19. #define __JUCE_THREAD_JUCEHEADER__
  20. #include "juce_WaitableEvent.h"
  21. #include "juce_CriticalSection.h"
  22. //==============================================================================
  23. /**
  24. Encapsulates a thread.
  25. Subclasses derive from Thread and implement the run() method, in which they
  26. do their business. The thread can then be started with the startThread() method
  27. and controlled with various other methods.
  28. This class also contains some thread-related static methods, such
  29. as sleep(), yield(), getCurrentThreadId() etc.
  30. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  31. MessageManagerLock
  32. */
  33. class JUCE_API Thread
  34. {
  35. public:
  36. //==============================================================================
  37. /**
  38. Creates a thread.
  39. When first created, the thread is not running. Use the startThread()
  40. method to start it.
  41. */
  42. explicit Thread (const String& threadName);
  43. /** Destructor.
  44. Deleting a Thread object that is running will only give the thread a
  45. brief opportunity to stop itself cleanly, so it's recommended that you
  46. should always call stopThread() with a decent timeout before deleting,
  47. to avoid the thread being forcibly killed (which is a Bad Thing).
  48. */
  49. virtual ~Thread();
  50. //==============================================================================
  51. /** Must be implemented to perform the thread's actual code.
  52. Remember that the thread must regularly check the threadShouldExit()
  53. method whilst running, and if this returns true it should return from
  54. the run() method as soon as possible to avoid being forcibly killed.
  55. @see threadShouldExit, startThread
  56. */
  57. virtual void run() = 0;
  58. //==============================================================================
  59. // Thread control functions..
  60. /** Starts the thread running.
  61. This will start the thread's run() method.
  62. (if it's already started, 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
  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. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  85. */
  86. void stopThread (int timeOutMilliseconds);
  87. //==============================================================================
  88. /** Returns true if the thread is currently active */
  89. bool isThreadRunning() const;
  90. /** Sets a flag to tell the thread it should stop.
  91. Calling this means that the threadShouldExit() method will then return true.
  92. The thread should be regularly checking this to see whether it should exit.
  93. If your thread makes use of wait(), you might want to call notify() after calling
  94. this method, to interrupt any waits that might be in progress, and allow it
  95. to reach a point where it can exit.
  96. @see threadShouldExit
  97. @see waitForThreadToExit
  98. */
  99. void signalThreadShouldExit();
  100. /** Checks whether the thread has been told to stop running.
  101. Threads need to check this regularly, and if it returns true, they should
  102. return from their run() method at the first possible opportunity.
  103. @see signalThreadShouldExit
  104. */
  105. inline bool threadShouldExit() const { return threadShouldExit_; }
  106. /** Waits for the thread to stop.
  107. This will waits until isThreadRunning() is false or until a timeout expires.
  108. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  109. is less than zero, it will wait forever.
  110. @returns true if the thread exits, or false if the timeout expires first.
  111. */
  112. bool waitForThreadToExit (int timeOutMilliseconds) const;
  113. //==============================================================================
  114. /** Changes the thread's priority.
  115. May return false if for some reason the priority can't be changed.
  116. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  117. of 5 is normal.
  118. */
  119. bool setPriority (int priority);
  120. /** Changes the priority of the caller thread.
  121. Similar to setPriority(), but this static method acts on the caller thread.
  122. May return false if for some reason the priority can't be changed.
  123. @see setPriority
  124. */
  125. static bool setCurrentThreadPriority (int priority);
  126. //==============================================================================
  127. /** Sets the affinity mask for the thread.
  128. This will only have an effect next time the thread is started - i.e. if the
  129. thread is already running when called, it'll have no effect.
  130. @see setCurrentThreadAffinityMask
  131. */
  132. void setAffinityMask (uint32 affinityMask);
  133. /** Changes the affinity mask for the caller thread.
  134. This will change the affinity mask for the thread that calls this static method.
  135. @see setAffinityMask
  136. */
  137. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  138. //==============================================================================
  139. // this can be called from any thread that needs to pause..
  140. static void JUCE_CALLTYPE sleep (int milliseconds);
  141. /** Yields the calling thread's current time-slot. */
  142. static void JUCE_CALLTYPE yield();
  143. //==============================================================================
  144. /** Makes the thread wait for a notification.
  145. This puts the thread to sleep until either the timeout period expires, or
  146. another thread calls the notify() method to wake it up.
  147. A negative time-out value means that the method will wait indefinitely.
  148. @returns true if the event has been signalled, false if the timeout expires.
  149. */
  150. bool wait (int timeOutMilliseconds) const;
  151. /** Wakes up the thread.
  152. If the thread has called the wait() method, this will wake it up.
  153. @see wait
  154. */
  155. void notify() const;
  156. //==============================================================================
  157. /** A value type used for thread IDs.
  158. @see getCurrentThreadId(), getThreadId()
  159. */
  160. typedef void* ThreadID;
  161. /** Returns an id that identifies the caller thread.
  162. To find the ID of a particular thread object, use getThreadId().
  163. @returns a unique identifier that identifies the calling thread.
  164. @see getThreadId
  165. */
  166. static ThreadID getCurrentThreadId();
  167. /** Finds the thread object that is currently running.
  168. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  169. object associated with them, so this will return 0.
  170. */
  171. static Thread* getCurrentThread();
  172. /** Returns the ID of this thread.
  173. That means the ID of this thread object - not of the thread that's calling the method.
  174. This can change when the thread is started and stopped, and will be invalid if the
  175. thread's not actually running.
  176. @see getCurrentThreadId
  177. */
  178. ThreadID getThreadId() const noexcept { return threadId_; }
  179. /** Returns the name of the thread.
  180. This is the name that gets set in the constructor.
  181. */
  182. const String& getThreadName() const { return threadName_; }
  183. /** Changes the name of the caller thread.
  184. Different OSes may place different length or content limits on this name.
  185. */
  186. static void setCurrentThreadName (const String& newThreadName);
  187. //==============================================================================
  188. /** Returns the number of currently-running threads.
  189. @returns the number of Thread objects known to be currently running.
  190. @see stopAllThreads
  191. */
  192. static int getNumRunningThreads();
  193. /** Tries to stop all currently-running threads.
  194. This will attempt to stop all the threads known to be running at the moment.
  195. */
  196. static void stopAllThreads (int timeoutInMillisecs);
  197. private:
  198. //==============================================================================
  199. const String threadName_;
  200. void* volatile threadHandle_;
  201. ThreadID threadId_;
  202. CriticalSection startStopLock;
  203. WaitableEvent startSuspensionEvent_, defaultEvent_;
  204. int threadPriority_;
  205. uint32 affinityMask_;
  206. bool volatile threadShouldExit_;
  207. #ifndef DOXYGEN
  208. friend void JUCE_API juce_threadEntryPoint (void*);
  209. #endif
  210. void launchThread();
  211. void closeThreadHandle();
  212. void killThread();
  213. void threadEntryPoint();
  214. static bool setThreadPriority (void*, int priority);
  215. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread);
  216. };
  217. #endif // __JUCE_THREAD_JUCEHEADER__