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