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.

316 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. jobNeedsRunningAgain /**< indicates that the job would like to be called
  64. again when a thread is free. */
  65. };
  66. /** Peforms the actual work that this job needs to do.
  67. Your subclass must implement this method, in which is does its work.
  68. If the code in this method takes a significant time to run, it must repeatedly check
  69. the shouldExit() method to see if something is trying to interrupt the job.
  70. If shouldExit() ever returns true, the runJob() method must return immediately.
  71. If this method returns jobHasFinished, then the job will be removed from the pool
  72. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  73. pool and will get a chance to run again as soon as a thread is free.
  74. @see shouldExit()
  75. */
  76. virtual JobStatus runJob() = 0;
  77. //==============================================================================
  78. /** Returns true if this job is currently running its runJob() method. */
  79. bool isRunning() const noexcept { return isActive; }
  80. /** Returns true if something is trying to interrupt this job and make it stop.
  81. Your runJob() method must call this whenever it gets a chance, and if it ever
  82. returns true, the runJob() method must return immediately.
  83. @see signalJobShouldExit()
  84. */
  85. bool shouldExit() const noexcept { return shouldStop; }
  86. /** Calling this will cause the shouldExit() method to return true, and the job
  87. should (if it's been implemented correctly) stop as soon as possible.
  88. @see shouldExit()
  89. */
  90. void signalJobShouldExit();
  91. //==============================================================================
  92. private:
  93. friend class ThreadPool;
  94. friend class ThreadPoolThread;
  95. String jobName;
  96. ThreadPool* pool;
  97. bool shouldStop, isActive, shouldBeDeleted;
  98. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob);
  99. };
  100. //==============================================================================
  101. /**
  102. A set of threads that will run a list of jobs.
  103. When a ThreadPoolJob object is added to the ThreadPool's list, its runJob() method
  104. will be called by the next pooled thread that becomes free.
  105. @see ThreadPoolJob, Thread
  106. */
  107. class JUCE_API ThreadPool
  108. {
  109. public:
  110. //==============================================================================
  111. /** Creates a thread pool.
  112. Once you've created a pool, you can give it some jobs by calling addJob().
  113. @param numberOfThreads the number of threads to run. These will be started
  114. immediately, and will run until the pool is deleted.
  115. */
  116. ThreadPool (int numberOfThreads);
  117. /** Creates a thread pool with one thread per CPU core.
  118. Once you've created a pool, you can give it some jobs by calling addJob().
  119. If you want to specify the number of threads, use the other constructor; this
  120. one creates a pool which has one thread for each CPU core.
  121. @see SystemStats::getNumCpus()
  122. */
  123. ThreadPool();
  124. /** Destructor.
  125. This will attempt to remove all the jobs before deleting, but if you want to
  126. specify a timeout, you should call removeAllJobs() explicitly before deleting
  127. the pool.
  128. */
  129. ~ThreadPool();
  130. //==============================================================================
  131. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  132. for some kind of operation.
  133. @see ThreadPool::removeAllJobs
  134. */
  135. class JUCE_API JobSelector
  136. {
  137. public:
  138. virtual ~JobSelector() {}
  139. /** Should return true if the specified thread matches your criteria for whatever
  140. operation that this object is being used for.
  141. Any implementation of this method must be extremely fast and thread-safe!
  142. */
  143. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  144. };
  145. //==============================================================================
  146. /** Adds a job to the queue.
  147. Once a job has been added, then the next time a thread is free, it will run
  148. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  149. runJob() method, the pool will either remove the job from the pool or add it to
  150. the back of the queue to be run again.
  151. If deleteJobWhenFinished is true, then the job object will be owned and deleted by
  152. the pool when not needed - if you do this, make sure that your object's destructor
  153. is thread-safe.
  154. If deleteJobWhenFinished is false, the pointer will be used but not deleted, and
  155. the caller is responsible for making sure the object is not deleted before it has
  156. been removed from the pool.
  157. */
  158. void addJob (ThreadPoolJob* job,
  159. bool deleteJobWhenFinished);
  160. /** Tries to remove a job from the pool.
  161. If the job isn't yet running, this will simply remove it. If it is running, it
  162. will wait for it to finish.
  163. If the timeout period expires before the job finishes running, then the job will be
  164. left in the pool and this will return false. It returns true if the job is sucessfully
  165. stopped and removed.
  166. @param job the job to remove
  167. @param interruptIfRunning if true, then if the job is currently busy, its
  168. ThreadPoolJob::signalJobShouldExit() method will be called to try
  169. to interrupt it. If false, then if the job will be allowed to run
  170. until it stops normally (or the timeout expires)
  171. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  172. before giving up and returning false
  173. */
  174. bool removeJob (ThreadPoolJob* job,
  175. bool interruptIfRunning,
  176. int timeOutMilliseconds);
  177. /** Tries to remove all jobs from the pool.
  178. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  179. methods called to try to interrupt them
  180. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  181. before giving up and returning false
  182. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  183. jobs should be removed. If it is zero, all jobs are removed
  184. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  185. expires while waiting for one or more jobs to stop
  186. */
  187. bool removeAllJobs (bool interruptRunningJobs,
  188. int timeOutMilliseconds,
  189. JobSelector* selectedJobsToRemove = nullptr);
  190. /** Returns the number of jobs currently running or queued.
  191. */
  192. int getNumJobs() const;
  193. /** Returns one of the jobs in the queue.
  194. Note that this can be a very volatile list as jobs might be continuously getting shifted
  195. around in the list, and this method may return 0 if the index is currently out-of-range.
  196. */
  197. ThreadPoolJob* getJob (int index) const;
  198. /** Returns true if the given job is currently queued or running.
  199. @see isJobRunning()
  200. */
  201. bool contains (const ThreadPoolJob* job) const;
  202. /** Returns true if the given job is currently being run by a thread.
  203. */
  204. bool isJobRunning (const ThreadPoolJob* job) const;
  205. /** Waits until a job has finished running and has been removed from the pool.
  206. This will wait until the job is no longer in the pool - i.e. until its
  207. runJob() method returns ThreadPoolJob::jobHasFinished.
  208. If the timeout period expires before the job finishes, this will return false;
  209. it returns true if the job has finished successfully.
  210. */
  211. bool waitForJobToFinish (const ThreadPoolJob* job,
  212. int timeOutMilliseconds) const;
  213. /** Returns a list of the names of all the jobs currently running or queued.
  214. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  215. */
  216. StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  217. /** Changes the priority of all the threads.
  218. This will call Thread::setPriority() for each thread in the pool.
  219. May return false if for some reason the priority can't be changed.
  220. */
  221. bool setThreadPriorities (int newPriority);
  222. private:
  223. //==============================================================================
  224. Array <ThreadPoolJob*> jobs;
  225. class ThreadPoolThread;
  226. friend class ThreadPoolThread;
  227. friend class OwnedArray <ThreadPoolThread>;
  228. OwnedArray <ThreadPoolThread> threads;
  229. CriticalSection lock;
  230. WaitableEvent jobFinishedSignal;
  231. bool runNextJob();
  232. ThreadPoolJob* pickNextJobToRun();
  233. void addToDeleteList (OwnedArray<ThreadPoolJob>&, ThreadPoolJob*) const;
  234. void createThreads (int numThreads);
  235. void stopThreads();
  236. // Note that this method has changed, and no longer has a parameter to indicate
  237. // whether the jobs should be deleted - see the new method for details.
  238. void removeAllJobs (bool, int, bool);
  239. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool);
  240. };
  241. #endif // __JUCE_THREADPOOL_JUCEHEADER__