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.

314 lines
13KB

  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_THREADPOOL_JUCEHEADER__
  19. #define __JUCE_THREADPOOL_JUCEHEADER__
  20. #include "juce_Thread.h"
  21. #include "../text/juce_StringArray.h"
  22. #include "../containers/juce_Array.h"
  23. #include "../containers/juce_OwnedArray.h"
  24. class ThreadPool;
  25. class ThreadPoolThread;
  26. //==============================================================================
  27. /**
  28. A task that is executed by a ThreadPool object.
  29. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  30. its threads.
  31. The runJob() method needs to be implemented to do the task, and if the code that
  32. does the work takes a significant time to run, it must keep checking the shouldExit()
  33. method to see if something is trying to interrupt the job. If shouldExit() returns
  34. true, the runJob() method must return immediately.
  35. @see ThreadPool, Thread
  36. */
  37. class JUCE_API ThreadPoolJob
  38. {
  39. public:
  40. //==============================================================================
  41. /** Creates a thread pool job object.
  42. After creating your job, add it to a thread pool with ThreadPool::addJob().
  43. */
  44. explicit ThreadPoolJob (const String& name);
  45. /** Destructor. */
  46. virtual ~ThreadPoolJob();
  47. //==============================================================================
  48. /** Returns the name of this job.
  49. @see setJobName
  50. */
  51. String getJobName() const;
  52. /** Changes the job's name.
  53. @see getJobName
  54. */
  55. void setJobName (const String& newName);
  56. //==============================================================================
  57. /** These are the values that can be returned by the runJob() method.
  58. */
  59. enum JobStatus
  60. {
  61. jobHasFinished = 0, /**< indicates that the job has finished and can be
  62. removed from the pool. */
  63. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  64. should be automatically deleted by the pool. */
  65. jobNeedsRunningAgain /**< indicates that the job would like to be called
  66. again when a thread is free. */
  67. };
  68. /** Peforms the actual work that this job needs to do.
  69. Your subclass must implement this method, in which is does its work.
  70. If the code in this method takes a significant time to run, it must repeatedly check
  71. the shouldExit() method to see if something is trying to interrupt the job.
  72. If shouldExit() ever returns true, the runJob() method must return immediately.
  73. If this method returns jobHasFinished, then the job will be removed from the pool
  74. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  75. pool and will get a chance to run again as soon as a thread is free.
  76. @see shouldExit()
  77. */
  78. virtual JobStatus runJob() = 0;
  79. //==============================================================================
  80. /** Returns true if this job is currently running its runJob() method. */
  81. bool isRunning() const { return isActive; }
  82. /** Returns true if something is trying to interrupt this job and make it stop.
  83. Your runJob() method must call this whenever it gets a chance, and if it ever
  84. returns true, the runJob() method must return immediately.
  85. @see signalJobShouldExit()
  86. */
  87. bool shouldExit() const { return shouldStop; }
  88. /** Calling this will cause the shouldExit() method to return true, and the job
  89. should (if it's been implemented correctly) stop as soon as possible.
  90. @see shouldExit()
  91. */
  92. void signalJobShouldExit();
  93. //==============================================================================
  94. private:
  95. friend class ThreadPool;
  96. friend class ThreadPoolThread;
  97. String jobName;
  98. ThreadPool* pool;
  99. bool shouldStop, isActive, shouldBeDeleted;
  100. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob);
  101. };
  102. //==============================================================================
  103. /**
  104. A set of threads that will run a list of jobs.
  105. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  106. will be called by the next pooled thread that becomes free.
  107. @see ThreadPoolJob, Thread
  108. */
  109. class JUCE_API ThreadPool
  110. {
  111. public:
  112. //==============================================================================
  113. /** Creates a thread pool.
  114. Once you've created a pool, you can give it some things to do with the addJob()
  115. method.
  116. @param numberOfThreads the maximum number of actual threads to run.
  117. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  118. until there are some jobs to run. If false, then
  119. all the threads will be fired-up immediately so that
  120. they're ready for action
  121. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  122. inactive for this length of time, they will automatically
  123. be stopped until more jobs come along and they're needed
  124. */
  125. ThreadPool (int numberOfThreads,
  126. bool startThreadsOnlyWhenNeeded = true,
  127. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  128. /** Destructor.
  129. This will attempt to remove all the jobs before deleting, but if you want to
  130. specify a timeout, you should call removeAllJobs() explicitly before deleting
  131. the pool.
  132. */
  133. ~ThreadPool();
  134. //==============================================================================
  135. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  136. for some kind of operation.
  137. @see ThreadPool::removeAllJobs
  138. */
  139. class JUCE_API JobSelector
  140. {
  141. public:
  142. virtual ~JobSelector() {}
  143. /** Should return true if the specified thread matches your criteria for whatever
  144. operation that this object is being used for.
  145. Any implementation of this method must be extremely fast and thread-safe!
  146. */
  147. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  148. };
  149. //==============================================================================
  150. /** Adds a job to the queue.
  151. Once a job has been added, then the next time a thread is free, it will run
  152. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  153. runJob() method, the pool will either remove the job from the pool or add it to
  154. the back of the queue to be run again.
  155. */
  156. void addJob (ThreadPoolJob* job);
  157. /** Tries to remove a job from the pool.
  158. If the job isn't yet running, this will simply remove it. If it is running, it
  159. will wait for it to finish.
  160. If the timeout period expires before the job finishes running, then the job will be
  161. left in the pool and this will return false. It returns true if the job is sucessfully
  162. stopped and removed.
  163. @param job the job to remove
  164. @param interruptIfRunning if true, then if the job is currently busy, its
  165. ThreadPoolJob::signalJobShouldExit() method will be called to try
  166. to interrupt it. If false, then if the job will be allowed to run
  167. until it stops normally (or the timeout expires)
  168. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  169. before giving up and returning false
  170. */
  171. bool removeJob (ThreadPoolJob* job,
  172. bool interruptIfRunning,
  173. int timeOutMilliseconds);
  174. /** Tries to remove all jobs from the pool.
  175. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  176. methods called to try to interrupt them
  177. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  178. before giving up and returning false
  179. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  180. they will simply be removed from the pool. Jobs that are already running when
  181. this method is called can choose whether they should be deleted by
  182. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  183. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  184. jobs should be removed. If it is zero, all jobs are removed
  185. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  186. expires while waiting for one or more jobs to stop
  187. */
  188. bool removeAllJobs (bool interruptRunningJobs,
  189. int timeOutMilliseconds,
  190. bool deleteInactiveJobs = false,
  191. JobSelector* selectedJobsToRemove = 0);
  192. /** Returns the number of jobs currently running or queued.
  193. */
  194. int getNumJobs() const;
  195. /** Returns one of the jobs in the queue.
  196. Note that this can be a very volatile list as jobs might be continuously getting shifted
  197. around in the list, and this method may return 0 if the index is currently out-of-range.
  198. */
  199. ThreadPoolJob* getJob (int index) const;
  200. /** Returns true if the given job is currently queued or running.
  201. @see isJobRunning()
  202. */
  203. bool contains (const ThreadPoolJob* job) const;
  204. /** Returns true if the given job is currently being run by a thread.
  205. */
  206. bool isJobRunning (const ThreadPoolJob* job) const;
  207. /** Waits until a job has finished running and has been removed from the pool.
  208. This will wait until the job is no longer in the pool - i.e. until its
  209. runJob() method returns ThreadPoolJob::jobHasFinished.
  210. If the timeout period expires before the job finishes, this will return false;
  211. it returns true if the job has finished successfully.
  212. */
  213. bool waitForJobToFinish (const ThreadPoolJob* job,
  214. int timeOutMilliseconds) const;
  215. /** Returns a list of the names of all the jobs currently running or queued.
  216. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  217. */
  218. StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  219. /** Changes the priority of all the threads.
  220. This will call Thread::setPriority() for each thread in the pool.
  221. May return false if for some reason the priority can't be changed.
  222. */
  223. bool setThreadPriorities (int newPriority);
  224. private:
  225. //==============================================================================
  226. const int threadStopTimeout;
  227. int priority;
  228. class ThreadPoolThread;
  229. friend class OwnedArray <ThreadPoolThread>;
  230. OwnedArray <ThreadPoolThread> threads;
  231. Array <ThreadPoolJob*> jobs;
  232. CriticalSection lock;
  233. uint32 lastJobEndTime;
  234. WaitableEvent jobFinishedSignal;
  235. friend class ThreadPoolThread;
  236. bool runNextJob();
  237. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool);
  238. };
  239. #endif // __JUCE_THREADPOOL_JUCEHEADER__