juce_ThreadPool.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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_THREADPOOL_H_INCLUDED
  22. #define JUCE_THREADPOOL_H_INCLUDED
  23. class ThreadPool;
  24. class ThreadPoolThread;
  25. //==============================================================================
  26. /**
  27. A task that is executed by a ThreadPool object.
  28. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  29. its threads.
  30. The runJob() method needs to be implemented to do the task, and if the code that
  31. does the work takes a significant time to run, it must keep checking the shouldExit()
  32. method to see if something is trying to interrupt the job. If shouldExit() returns
  33. true, the runJob() method must return immediately.
  34. @see ThreadPool, Thread
  35. */
  36. class JUCE_API ThreadPoolJob
  37. {
  38. public:
  39. //==============================================================================
  40. /** Creates a thread pool job object.
  41. After creating your job, add it to a thread pool with ThreadPool::addJob().
  42. */
  43. explicit ThreadPoolJob (const String& name);
  44. /** Destructor. */
  45. virtual ~ThreadPoolJob();
  46. //==============================================================================
  47. /** Returns the name of this job.
  48. @see setJobName
  49. */
  50. String getJobName() const;
  51. /** Changes the job's name.
  52. @see getJobName
  53. */
  54. void setJobName (const String& newName);
  55. //==============================================================================
  56. /** These are the values that can be returned by the runJob() method.
  57. */
  58. enum JobStatus
  59. {
  60. jobHasFinished = 0, /**< indicates that the job has finished and can be
  61. removed from the pool. */
  62. jobNeedsRunningAgain /**< indicates that the job would like to be called
  63. again when a thread is free. */
  64. };
  65. /** Peforms the actual work that this job needs to do.
  66. Your subclass must implement this method, in which is does its work.
  67. If the code in this method takes a significant time to run, it must repeatedly check
  68. the shouldExit() method to see if something is trying to interrupt the job.
  69. If shouldExit() ever returns true, the runJob() method must return immediately.
  70. If this method returns jobHasFinished, then the job will be removed from the pool
  71. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  72. pool and will get a chance to run again as soon as a thread is free.
  73. @see shouldExit()
  74. */
  75. virtual JobStatus runJob() = 0;
  76. //==============================================================================
  77. /** Returns true if this job is currently running its runJob() method. */
  78. bool isRunning() const noexcept { return isActive; }
  79. /** Returns true if something is trying to interrupt this job and make it stop.
  80. Your runJob() method must call this whenever it gets a chance, and if it ever
  81. returns true, the runJob() method must return immediately.
  82. @see signalJobShouldExit()
  83. */
  84. bool shouldExit() const noexcept { return shouldStop; }
  85. /** Calling this will cause the shouldExit() method to return true, and the job
  86. should (if it's been implemented correctly) stop as soon as possible.
  87. @see shouldExit()
  88. */
  89. void signalJobShouldExit();
  90. //==============================================================================
  91. /** If the calling thread is being invoked inside a runJob() method, this will
  92. return the ThreadPoolJob that it belongs to.
  93. */
  94. static ThreadPoolJob* getCurrentThreadPoolJob();
  95. //==============================================================================
  96. private:
  97. friend class ThreadPool;
  98. friend class ThreadPoolThread;
  99. String jobName;
  100. ThreadPool* pool;
  101. bool shouldStop, isActive, shouldBeDeleted;
  102. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob)
  103. };
  104. //==============================================================================
  105. /**
  106. A set of threads that will run a list of jobs.
  107. When a ThreadPoolJob object is added to the ThreadPool's list, its runJob() method
  108. will be called by the next pooled thread that becomes free.
  109. @see ThreadPoolJob, Thread
  110. */
  111. class JUCE_API ThreadPool
  112. {
  113. public:
  114. //==============================================================================
  115. /** Creates a thread pool.
  116. Once you've created a pool, you can give it some jobs by calling addJob().
  117. @param numberOfThreads the number of threads to run. These will be started
  118. immediately, and will run until the pool is deleted.
  119. */
  120. ThreadPool (int numberOfThreads);
  121. /** Creates a thread pool with one thread per CPU core.
  122. Once you've created a pool, you can give it some jobs by calling addJob().
  123. If you want to specify the number of threads, use the other constructor; this
  124. one creates a pool which has one thread for each CPU core.
  125. @see SystemStats::getNumCpus()
  126. */
  127. ThreadPool();
  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. If deleteJobWhenFinished is true, then the job object will be owned and deleted by
  156. the pool when not needed - if you do this, make sure that your object's destructor
  157. is thread-safe.
  158. If deleteJobWhenFinished is false, the pointer will be used but not deleted, and
  159. the caller is responsible for making sure the object is not deleted before it has
  160. been removed from the pool.
  161. */
  162. void addJob (ThreadPoolJob* job,
  163. bool deleteJobWhenFinished);
  164. /** Tries to remove a job from the pool.
  165. If the job isn't yet running, this will simply remove it. If it is running, it
  166. will wait for it to finish.
  167. If the timeout period expires before the job finishes running, then the job will be
  168. left in the pool and this will return false. It returns true if the job is successfully
  169. stopped and removed.
  170. @param job the job to remove
  171. @param interruptIfRunning if true, then if the job is currently busy, its
  172. ThreadPoolJob::signalJobShouldExit() method will be called to try
  173. to interrupt it. If false, then if the job will be allowed to run
  174. until it stops normally (or the timeout expires)
  175. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  176. before giving up and returning false
  177. */
  178. bool removeJob (ThreadPoolJob* job,
  179. bool interruptIfRunning,
  180. int timeOutMilliseconds);
  181. /** Tries to remove all jobs from the pool.
  182. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  183. methods called to try to interrupt them
  184. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  185. before giving up and returning false
  186. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  187. jobs should be removed. If it is zero, all jobs are removed
  188. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  189. expires while waiting for one or more jobs to stop
  190. */
  191. bool removeAllJobs (bool interruptRunningJobs,
  192. int timeOutMilliseconds,
  193. JobSelector* selectedJobsToRemove = nullptr);
  194. /** Returns the number of jobs currently running or queued.
  195. */
  196. int getNumJobs() const;
  197. /** Returns one of the jobs in the queue.
  198. Note that this can be a very volatile list as jobs might be continuously getting shifted
  199. around in the list, and this method may return nullptr if the index is currently out-of-range.
  200. */
  201. ThreadPoolJob* getJob (int index) const;
  202. /** Returns true if the given job is currently queued or running.
  203. @see isJobRunning()
  204. */
  205. bool contains (const ThreadPoolJob* job) const;
  206. /** Returns true if the given job is currently being run by a thread.
  207. */
  208. bool isJobRunning (const ThreadPoolJob* job) const;
  209. /** Waits until a job has finished running and has been removed from the pool.
  210. This will wait until the job is no longer in the pool - i.e. until its
  211. runJob() method returns ThreadPoolJob::jobHasFinished.
  212. If the timeout period expires before the job finishes, this will return false;
  213. it returns true if the job has finished successfully.
  214. */
  215. bool waitForJobToFinish (const ThreadPoolJob* job,
  216. int timeOutMilliseconds) const;
  217. /** Returns a list of the names of all the jobs currently running or queued.
  218. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  219. */
  220. StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  221. /** Changes the priority of all the threads.
  222. This will call Thread::setPriority() for each thread in the pool.
  223. May return false if for some reason the priority can't be changed.
  224. */
  225. bool setThreadPriorities (int newPriority);
  226. private:
  227. //==============================================================================
  228. Array <ThreadPoolJob*> jobs;
  229. class ThreadPoolThread;
  230. friend class ThreadPoolJob;
  231. friend class ThreadPoolThread;
  232. friend struct ContainerDeletePolicy<ThreadPoolThread>;
  233. OwnedArray<ThreadPoolThread> threads;
  234. CriticalSection lock;
  235. WaitableEvent jobFinishedSignal;
  236. bool runNextJob (ThreadPoolThread&);
  237. ThreadPoolJob* pickNextJobToRun();
  238. void addToDeleteList (OwnedArray<ThreadPoolJob>&, ThreadPoolJob*) const;
  239. void createThreads (int numThreads);
  240. void stopThreads();
  241. // Note that this method has changed, and no longer has a parameter to indicate
  242. // whether the jobs should be deleted - see the new method for details.
  243. void removeAllJobs (bool, int, bool);
  244. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool)
  245. };
  246. #endif // JUCE_THREADPOOL_H_INCLUDED