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.

315 lines
13KB

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