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.

293 lines
11KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 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. #include "../containers/juce_Array.h"
  23. //==============================================================================
  24. /**
  25. Encapsulates a thread.
  26. Subclasses derive from Thread and implement the run() method, in which they
  27. do their business. The thread can then be started with the startThread() method
  28. and controlled with various other methods.
  29. This class also contains some thread-related static methods, such
  30. as sleep(), yield(), getCurrentThreadId() etc.
  31. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  32. MessageManagerLock
  33. */
  34. class JUCE_API Thread
  35. {
  36. public:
  37. //==============================================================================
  38. /**
  39. Creates a thread.
  40. When first created, the thread is not running. Use the startThread()
  41. method to start it.
  42. */
  43. Thread (const String& threadName);
  44. /** Destructor.
  45. Deleting a Thread object that is running will only give the thread a
  46. brief opportunity to stop itself cleanly, so it's recommended that you
  47. should always call stopThread() with a decent timeout before deleting,
  48. to avoid the thread being forcibly killed (which is a Bad Thing).
  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 start the thread's run() method.
  63. (if it's already started, 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
  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. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  86. */
  87. void stopThread (int timeOutMilliseconds);
  88. //==============================================================================
  89. /** Returns true if the thread is currently active */
  90. bool isThreadRunning() const;
  91. /** Sets a flag to tell the thread it should stop.
  92. Calling this means that the threadShouldExit() method will then return true.
  93. The thread should be regularly checking this to see whether it should exit.
  94. @see threadShouldExit
  95. @see waitForThreadToExit
  96. */
  97. void signalThreadShouldExit();
  98. /** Checks whether the thread has been told to stop running.
  99. Threads need to check this regularly, and if it returns true, they should
  100. return from their run() method at the first possible opportunity.
  101. @see signalThreadShouldExit
  102. */
  103. inline bool threadShouldExit() const { return threadShouldExit_; }
  104. /** Waits for the thread to stop.
  105. This will waits until isThreadRunning() is false or until a timeout expires.
  106. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  107. is less than zero, it will wait forever.
  108. @returns true if the thread exits, or false if the timeout expires first.
  109. */
  110. bool waitForThreadToExit (int timeOutMilliseconds) const;
  111. //==============================================================================
  112. /** Changes the thread's priority.
  113. May return false if for some reason the priority can't be changed.
  114. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  115. of 5 is normal.
  116. */
  117. bool setPriority (int priority);
  118. /** Changes the priority of the caller thread.
  119. Similar to setPriority(), but this static method acts on the caller thread.
  120. May return false if for some reason the priority can't be changed.
  121. @see setPriority
  122. */
  123. static bool setCurrentThreadPriority (int priority);
  124. //==============================================================================
  125. /** Sets the affinity mask for the thread.
  126. This will only have an effect next time the thread is started - i.e. if the
  127. thread is already running when called, it'll have no effect.
  128. @see setCurrentThreadAffinityMask
  129. */
  130. void setAffinityMask (uint32 affinityMask);
  131. /** Changes the affinity mask for the caller thread.
  132. This will change the affinity mask for the thread that calls this static method.
  133. @see setAffinityMask
  134. */
  135. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  136. //==============================================================================
  137. // this can be called from any thread that needs to pause..
  138. static void JUCE_CALLTYPE sleep (int milliseconds);
  139. /** Yields the calling thread's current time-slot. */
  140. static void JUCE_CALLTYPE yield();
  141. //==============================================================================
  142. /** Makes the thread wait for a notification.
  143. This puts the thread to sleep until either the timeout period expires, or
  144. another thread calls the notify() method to wake it up.
  145. @returns true if the event has been signalled, false if the timeout expires.
  146. */
  147. bool wait (int timeOutMilliseconds) const;
  148. /** Wakes up the thread.
  149. If the thread has called the wait() method, this will wake it up.
  150. @see wait
  151. */
  152. void notify() const;
  153. //==============================================================================
  154. /** A value type used for thread IDs.
  155. @see getCurrentThreadId(), getThreadId()
  156. */
  157. typedef void* ThreadID;
  158. /** Returns an id that identifies the caller thread.
  159. To find the ID of a particular thread object, use getThreadId().
  160. @returns a unique identifier that identifies the calling thread.
  161. @see getThreadId
  162. */
  163. static ThreadID getCurrentThreadId();
  164. /** Finds the thread object that is currently running.
  165. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  166. object associated with them, so this will return 0.
  167. */
  168. static Thread* getCurrentThread();
  169. /** Returns the ID of this thread.
  170. That means the ID of this thread object - not of the thread that's calling the method.
  171. This can change when the thread is started and stopped, and will be invalid if the
  172. thread's not actually running.
  173. @see getCurrentThreadId
  174. */
  175. ThreadID getThreadId() const throw() { return threadId_; }
  176. /** Returns the name of the thread.
  177. This is the name that gets set in the constructor.
  178. */
  179. const String getThreadName() const { return threadName_; }
  180. //==============================================================================
  181. /** Returns the number of currently-running threads.
  182. @returns the number of Thread objects known to be currently running.
  183. @see stopAllThreads
  184. */
  185. static int getNumRunningThreads();
  186. /** Tries to stop all currently-running threads.
  187. This will attempt to stop all the threads known to be running at the moment.
  188. */
  189. static void stopAllThreads (int timeoutInMillisecs);
  190. //==============================================================================
  191. juce_UseDebuggingNewOperator
  192. private:
  193. const String threadName_;
  194. void* volatile threadHandle_;
  195. CriticalSection startStopLock;
  196. WaitableEvent startSuspensionEvent_, defaultEvent_;
  197. int threadPriority_;
  198. ThreadID threadId_;
  199. uint32 affinityMask_;
  200. bool volatile threadShouldExit_;
  201. friend void JUCE_API juce_threadEntryPoint (void*);
  202. static void threadEntryPoint (Thread* thread);
  203. static Array<Thread*> runningThreads;
  204. static CriticalSection runningThreadsLock;
  205. Thread (const Thread&);
  206. Thread& operator= (const Thread&);
  207. };
  208. #endif // __JUCE_THREAD_JUCEHEADER__