juce_Thread.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. or without fee is hereby granted, provided that the above copyright notice and this
  7. permission notice appear in all copies.
  8. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  9. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  10. NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  11. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  12. IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. ------------------------------------------------------------------------------
  15. NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
  16. All other JUCE modules are covered by a dual GPL/commercial license, so if you are
  17. using any other modules, be sure to check that you also comply with their license.
  18. For more details, visit www.juce.com
  19. ==============================================================================
  20. */
  21. #ifndef JUCE_THREAD_H_INCLUDED
  22. #define JUCE_THREAD_H_INCLUDED
  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. explicit Thread (const String& threadName);
  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
  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
  107. */
  108. inline bool threadShouldExit() const { return shouldExit; }
  109. /** Waits for the thread to stop.
  110. This will waits until isThreadRunning() is false or until a timeout expires.
  111. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  112. is less than zero, it will wait forever.
  113. @returns true if the thread exits, or false if the timeout expires first.
  114. */
  115. bool waitForThreadToExit (int timeOutMilliseconds) const;
  116. //==============================================================================
  117. /** Changes the thread's priority.
  118. May return false if for some reason the priority can't be changed.
  119. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  120. of 5 is normal.
  121. */
  122. bool setPriority (int priority);
  123. /** Changes the priority of the caller thread.
  124. Similar to setPriority(), but this static method acts on the caller thread.
  125. May return false if for some reason the priority can't be changed.
  126. @see setPriority
  127. */
  128. static bool setCurrentThreadPriority (int priority);
  129. //==============================================================================
  130. /** Sets the affinity mask for the thread.
  131. This will only have an effect next time the thread is started - i.e. if the
  132. thread is already running when called, it'll have no effect.
  133. @see setCurrentThreadAffinityMask
  134. */
  135. void setAffinityMask (uint32 affinityMask);
  136. /** Changes the affinity mask for the caller thread.
  137. This will change the affinity mask for the thread that calls this static method.
  138. @see setAffinityMask
  139. */
  140. static void JUCE_CALLTYPE setCurrentThreadAffinityMask (uint32 affinityMask);
  141. //==============================================================================
  142. // this can be called from any thread that needs to pause..
  143. static void JUCE_CALLTYPE sleep (int milliseconds);
  144. /** Yields the calling thread's current time-slot. */
  145. static void JUCE_CALLTYPE yield();
  146. //==============================================================================
  147. /** Makes the thread wait for a notification.
  148. This puts the thread to sleep until either the timeout period expires, or
  149. another thread calls the notify() method to wake it up.
  150. A negative time-out value means that the method will wait indefinitely.
  151. @returns true if the event has been signalled, false if the timeout expires.
  152. */
  153. bool wait (int timeOutMilliseconds) const;
  154. /** Wakes up the thread.
  155. If the thread has called the wait() method, this will wake it up.
  156. @see wait
  157. */
  158. void notify() const;
  159. //==============================================================================
  160. /** A value type used for thread IDs.
  161. @see getCurrentThreadId(), getThreadId()
  162. */
  163. typedef void* ThreadID;
  164. /** Returns an id that identifies the caller thread.
  165. To find the ID of a particular thread object, use getThreadId().
  166. @returns a unique identifier that identifies the calling thread.
  167. @see getThreadId
  168. */
  169. static ThreadID JUCE_CALLTYPE getCurrentThreadId();
  170. /** Finds the thread object that is currently running.
  171. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  172. object associated with them, so this will return 0.
  173. */
  174. static Thread* JUCE_CALLTYPE getCurrentThread();
  175. /** Returns the ID of this thread.
  176. That means the ID of this thread object - not of the thread that's calling the method.
  177. This can change when the thread is started and stopped, and will be invalid if the
  178. thread's not actually running.
  179. @see getCurrentThreadId
  180. */
  181. ThreadID getThreadId() const noexcept { return threadId; }
  182. /** Returns the name of the thread.
  183. This is the name that gets set in the constructor.
  184. */
  185. const String& getThreadName() const { return threadName; }
  186. /** Changes the name of the caller thread.
  187. Different OSes may place different length or content limits on this name.
  188. */
  189. static void JUCE_CALLTYPE setCurrentThreadName (const String& newThreadName);
  190. private:
  191. //==============================================================================
  192. const String threadName;
  193. void* volatile threadHandle;
  194. ThreadID threadId;
  195. CriticalSection startStopLock;
  196. WaitableEvent startSuspensionEvent, defaultEvent;
  197. int threadPriority;
  198. uint32 affinityMask;
  199. bool volatile shouldExit;
  200. #ifndef DOXYGEN
  201. friend void JUCE_API juce_threadEntryPoint (void*);
  202. #endif
  203. void launchThread();
  204. void closeThreadHandle();
  205. void killThread();
  206. void threadEntryPoint();
  207. static bool setThreadPriority (void*, int);
  208. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread)
  209. };
  210. #endif // JUCE_THREAD_H_INCLUDED